Introduction
Swapping two variables is a common operation in programming, where the values of two variables are exchanged. This guide will demonstrate how to write a simple Go program to swap two variables using a temporary variable.
Problem Statement
Create a Go program that:
- Prompts the user to enter two numbers.
- Swaps the values of the two numbers.
- Displays the values after swapping.
Example:
- Input: a = 5,b = 10
- Output: a = 10,b = 5
Solution Steps
- Import the fmt Package: Use import "fmt"to include the fmt package for formatted I/O operations.
- Write the Main Function: Define the mainfunction, which is the entry point of every Go program.
- Declare Variables: Declare variables to store the two numbers and a temporary variable to assist in the swapping process.
- Input the Numbers: Use fmt.Scanlnto take input from the user for the two numbers.
- Swap the Values: Use a temporary variable to swap the values of the two numbers.
- Display the Swapped Values: Use fmt.Printlnto display the values after swapping.
Go Program
package main
import "fmt"
/**
 * Go Program to Swap Two Variables
 * Author: https://www.javaguides.net/
 */
func main() {
    // Step 1: Declare variables to hold the numbers and a temporary variable
    var a, b, temp int
    // Step 2: Prompt the user to enter the first number
    fmt.Print("Enter the first number (a): ")
    fmt.Scanln(&a)
    // Step 3: Prompt the user to enter the second number
    fmt.Print("Enter the second number (b): ")
    fmt.Scanln(&b)
    // Step 4: Swap the values using a temporary variable
    temp = a
    a = b
    b = temp
    // Step 5: Display the swapped values
    fmt.Println("After swapping, the values are:")
    fmt.Println("a =", a)
    fmt.Println("b =", b)
}
Explanation
Step 1: Declare Variables
- The variables aandbare declared as integers to store the two input numbers. A temporary variabletempis used to assist in swapping the values.
Step 2: Input the First Number
- The program prompts the user to enter the first number, which is stored in the variable a.
Step 3: Input the Second Number
- The program prompts the user to enter the second number, which is stored in the variable b.
Step 4: Swap the Values
- The value of ais assigned totemp, thenbis assigned toa, and finallytempis assigned tob. This effectively swaps the values ofaandb.
Step 5: Display the Swapped Values
- The program displays the values of aandbafter swapping.
Output Example
Example:
Enter the first number (a): 5
Enter the second number (b): 10
After swapping, the values are:
a = 10
b = 5
Conclusion
This Go program illustrates how to swap two variables using a temporary variable. Swapping values is a fundamental concept in programming and is useful in various scenarios, such as sorting algorithms and data manipulation. This example provides a clear understanding for beginners learning Go programming.