Golang Program to swap two numbers

April 23, 2022, Learn eTutorial

For a better understanding of this example, we always recommend you to learn the basic topics of Golang programming listed below:

 Swapping of two numbers

Swapping of two numbers means exchanging the value of two variables.
For example we have two variables v1 and v2. The value of v1 is 10 and v2 is 20. After swapping the value of v1 will become 20 and v2 will become 10.

How to swap two numbers in the GO Program

Here we are showing how to swap two numbers in the Go language. Here variables x,y are holding the numbers to swap, and another variable temp is used for helping the swapping. First, move the first variable x to the temp variable, and move the second variable y to the first variable x. Finally, move the temp variable into the second variable y. Given below are the steps which are used in the Go program. 


STEP 1: Import the package fmt

STEP 2: Start function main()

STEP 3: Declare the variable x, y, temp

STEP 4: Read the first number x using fmt.Scanfln()

STEP 5: Read the second number y using fmt.Scanfln()

STEP 6: Move x into temp as temp=x

STEP 7: Move y into x as x=y

STEP8: Move temp into y as y=temp

STEP9: Finally print x,y using fmt.Println()


Golang Source Code

                                          package main
import "fmt"

func main()  {
    var x, y, temp int
    fmt.Print("Enter the first number x = ")
    fmt.Print("Enter the second number y = ")

    temp = x
    x = y
    y = temp

    fmt.Println("The first number after swap  = ", x)
    fmt.Println("The second number after swap = ", y)


Enter the first number x = 13
Enter the second number y = 28
The first number after swap  =  28
The second number after swap =  13