Go Program to Swap Two Numbers Without Using a Temporary Variable

1. Introduction

Swapping numbers is one of the fundamental operations in computing. Traditionally, a third (temporary) variable is used to facilitate the swap. However, there are techniques to achieve this without the need for an auxiliary variable. In this post, we dive into a Go program that demonstrates this intriguing method.

2. Program Overview

The Go program to be discussed accomplishes the following:

1. Initialize two integers.

2. Perform the swapping operation without using a temporary variable.

3. Display the results before and after the swap.

3. Code Program

package main

import "fmt"

func main() {
    a, b := 5, 10
    
    fmt.Println("Before swap: a =", a, ", b =", b)
    
    // Swapping without using temporary variable
    a, b = b, a
    
    fmt.Println("After swap: a =", a, ", b =", b)
}

Output:

Before swap: a = 5 , b = 10
After swap: a = 10 , b = 5

4. Step By Step Explanation

1. Initialization: We start by initializing two variables a and b with values 5 and 10 respectively.

2. Swapping Logic: The line a, b = b, a is where the magic happens. This is an idiomatic Go way of swapping two variables without the need for a third variable. This tuple assignment technique assigns multiple variables at once, effectively exchanging their values.

3. Printing the results: We display the values of a and b both before and after the swap for clarity.

The tuple assignment method of swapping values is efficient and concise, and it's one of the distinct features that make Go an elegant language.

Note: Tuple assignment for swapping works in some other programming languages as well, but it's always good to be aware of the capabilities of the language you're working with.

Comments