Thursday, December 13, 2018

Golang Example - 2 ways to find swap two numbers/variables

In this post, This convers 2 ways to swap two numbers or variables in Golang.
First one is to swap variables in temporary variable, another one is not using temporary variable.

Example 1: Swap two values/numbers using a temporary variable

package main

import (
 "fmt"
)

func main() {
 number1, number2 := 12, 30
 fmt.Println("Before Swap process")
 fmt.Println("Number1:", number1)
 fmt.Println("Number2:", number2)

 // number1 is assigned to temporary variable
 temporary := number1
 // number1 is assigned to number2 variable
 number1 = number2
 //  temporary  is assigned to number2
 number2 = temporary

 fmt.Println("After Swap process")
 fmt.Println("Number1:", number1)
 fmt.Println("Number2:", number2)
}
The above program is compiled and executed, Output is
Before Swap process
Number1: 12
Number2: 30
After Swap process
Number1: 30
Number2: 12
In the above, Two variables number1 and number 2 are declared, and assigned with 12 and 30 values respectively.
Here is a swapping process
  • First, the number1 variable value is assigned to a temporary variable
  • Next is, nthe umber2 variable value is assigned to the number1 variable
  • Finallyl, temporary (intiall number1 variable value) value is assigned to number2 variable value 

Here temporary variable is declared and used to store the number1 value before doing swapping. number1 and number2 variable values are printed to console before and after swapping process using Println function

Example 2 swap numbers without a temporary variable

 In this program, Numbers are swapped without using a temporary variable. Here tuple assignments are used to swap the numbers Swapped numbers areprinted to console using println function Here is an program swap number using tuple assignment
package main

import (
 "fmt"
)

func main() {
 number1, number2 := 12, 30
 fmt.Println("Before Swap process")
 fmt.Println("Number1:", number1)
 fmt.Println("Number2:", number2)
 number1, number2 = number2, number1

 fmt.Println("After Swap process")
 fmt.Println("Number1:", number1)
 fmt.Println("Number2:", number2)
}
Output is
Before Swap process
Number1: 12
Number2: 30
After Swap process
Number1: 30
Number2: 12

Related article


EmoticonEmoticon