Techieindoor

Go – Program to Swap two numbers in golang

Here, we will see program to Swap two numbers in golang. Given below, you can find algorithm and program.

Given two values in variables let us say a and b. We have to swap these two values in go.

Algorithm:

Input : 
a = 4
b = 10

Output : 
a = 10
b = 4

Input : 
a = 5
b = -3

Output :
a = -3
b = 5

Code:

package main
 
import (
 
  "fmt"
 
)
 
func swap_values(a *int, b *int) {
 
  var tmp = *a
 
  *a = *b
 
  *b = tmp
 
}
 
func main() {
 
  var a = 4
 
  var b = 10
 
  fmt.Printf("Before swap: a = %d, b = %d \n", a, b)
 
  // swap the values
  swap_values(&a, &b)
 
  fmt.Printf("After swap: a = %d, b = %d \n", a, b)
   
}

Output:

Before swap: a = 4, b = 10

After swap: a = 10, b = 4

To learn more about golang. Please follow given below link.

https://www.techieindoor.com/go-lang/

References:

https://golang.org/doc/
https://golang.org/pkg/

Exit mobile version