GO Program to swap two numbers

How to swap two numbers

Here we are explaining how to swap two numbers in the Go program. We can use the built-in function fmt.println() to print anything and fmt.scanln() for reading the values. This function is defined under the fmt package and it helps to write standard output. In order to use these functions, we need to import the “fmt” package.


How to swap two numbers in the GO Program

We are using fmt.println() function for printing the string to the output screen. 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()


GO 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