Swap Two Numbers in Go
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
Example 1: Swapping two numbers using a temporary variable
We can use a temporary variable to swap the values of two variables.
For example,
- Define a function named
swapWithTemp
that takes two parametersa
andb
of typeint
. - Use a temporary variable
temp
to hold the value ofa
. - Assign the value of
b
toa
. - Assign the value of
temp
(original value ofa
) tob
. - Return the swapped values of
a
andb
. - 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
Example 2: Swapping two numbers using multiple assignment
We can use multiple assignment to swap the values of two variables in a single line.
For example,
- Define a function named
swapWithMultipleAssignment
that takes two parametersa
andb
of typeint
. - Use multiple assignment to swap the values of
a
andb
in a single line. - Return the swapped values of
a
andb
. - 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