Go Tutorials

Go Programs

Go Swap Two Numbers


Go Swap Two Numbers

In this tutorial, we will learn how to swap two numbers in Go. We will cover two methods: using a temporary variable and using multiple assignment to swap the values of two variables.


What is Swapping

Swapping refers to the process of exchanging the values of two variables. This can be useful in various programming scenarios where the order or value of variables needs to be interchanged.


Syntax

The syntax to swap two numbers in Go can be done in two ways:

// Using a temporary variable
func swapWithTemp(a, b int) (int, int) {
    temp := a
    a = b
    b = temp
    return a, b
}

// Using multiple assignment
func swapWithMultipleAssignment(a, b int) (int, int) {
    a, b = b, a
    return a, b
}


Youtube Learning Video



Swapping two numbers using a temporary variable

We can use a temporary variable to swap the values of two variables.

For example,

  1. Define a function named swapWithTemp that takes two parameters a and b of type int.
  2. Use a temporary variable temp to hold the value of a.
  3. Assign the value of b to a.
  4. Assign the value of temp (original value of a) to b.
  5. Return the swapped values of a and b.
  6. In the main function, call the swapWithTemp function with sample values and print the result.

Go Program

package main

import (
    "fmt"
)

func swapWithTemp(a, b int) (int, int) {
    temp := a
    a = b
    b = temp
    return a, b
}

func main() {
    a, b := 5, 10
    fmt.Printf("Before swapping: a = %d, b = %d\n", a, b)
    a, b = swapWithTemp(a, b)
    fmt.Printf("After swapping with temp variable: a = %d, b = %d\n", a, b)
}

Output

Before swapping: a = 5, b = 10
After swapping with temp variable: a = 10, b = 5


Swapping two numbers using multiple assignment

We can use multiple assignment to swap the values of two variables in a single line.

For example,

  1. Define a function named swapWithMultipleAssignment that takes two parameters a and b of type int.
  2. Use multiple assignment to swap the values of a and b in a single line.
  3. Return the swapped values of a and b.
  4. In the main function, call the swapWithMultipleAssignment function with sample values and print the result.

Go Program

package main

import (
    "fmt"
)

func swapWithMultipleAssignment(a, b int) (int, int) {
    a, b = b, a
    return a, b
}

func main() {
    a, b := 5, 10
    fmt.Printf("Before swapping: a = %d, b = %d\n", a, b)
    a, b = swapWithMultipleAssignment(a, b)
    fmt.Printf("After swapping with multiple assignment: a = %d, b = %d\n", a, b)
}

Output

Before swapping: a = 5, b = 10
After swapping with multiple assignment: a = 10, b = 5