# Write a Golang program to swap two numbers without using a third variable

Go ProgrammingServer Side ProgrammingProgramming

#### Cyber Security : Go from Zero to Hero

Most Popular

60 Lectures 5.5 hours

#### Master C and Embedded C Programming- Learn as you go

66 Lectures 5.5 hours

#### C Programming from scratch- Master C Programming

Best Seller

60 Lectures 8 hours

## Approach to solve this problem

• Step 1: Define a function that accepts two numbers, type is int.
• Step 2: Find b = a + b;
• Step 3: Then a = b – a and b = b – a

## Program

Live Demo

package main
import "fmt"

func swap(a, b int){
fmt.Printf("Before swapping, numbers are %d and %d\n", a, b)
b = a + b
a = b - a
b = b - a
fmt.Printf("After swapping, numbers are %d and %d\n", a, b)
}

func main(){
swap(23, 45)
swap(56, 100)
}

## Output

Before swapping, numbers are 23 and 45
After swapping, numbers are 45 and 23
Before swapping, numbers are 56 and 100
After swapping, numbers are 100 and 56
Updated on 04-Feb-2021 10:55:07