C++ Program to Swap Two Numbers

Last Updated : 31 Mar, 2026

Swapping numbers is the process of interchanging their values. In this article, we will learn algorithms and code to swap two numbers in the C++ programming language.

after_swapping
Swapping changes the values stored in variables, not their memory locations.

1. Swap Numbers Using a Temporary Variable

We can swap the values of the given two numbers by using another variable to temporarily store the value as we swap the variables' data. The below steps shows how to use the temporary variable to swap values.

Steps

  • Assign a to a temp variable: temp = a
  • Assign b to a: a = b
  • Assign temp to b: b = temp

Code Example:

C++
#include <bits/stdc++.h>
using namespace std;

int main(){
    int a = 2, b = 3;

    cout << "Before swapping a = " << a << " , b = " << b << endl;

    int temp;
    
    temp = a;
    a = b;
    b = temp;
    cout << "After swapping a = " << a << " , b = " << b << endl;
    return 0;
}

Output
Before swapping a = 2 , b = 3
After swapping a = 3 , b = 2

2. Swap Numbers Without Using a Temporary Variable

We can also swap numbers without using a temporary variable by using arithmetic operations. However, this method is not always safe because it may cause overflow when working with large values. Therefore, it is generally recommended to use a temporary variable or std::swap() instead.

Steps

  • Assign to b the sum of a and b i.e. b = a + b.
  • Assign to a difference of b and a i.e. a = b - a.
  • Assign to b the difference of b and a i.e. b = b - a.

Code Example:

C++
#include <bits/stdc++.h>
using namespace std;

int main(){
    int a = 2, b = 3;

    cout << "Before swapping a = " << a << " , b = " << b << endl;

    b = a + b;
    a = b - a;
    b = b - a;

    cout << "After swapping a = " << a << " , b = " << b << endl;
    return 0;
}

Output
Before swapping a = 2 , b = 3
After swapping a = 3 , b = 2

3. Swap Two Numbers Using Inbuilt Function

C++ Standard Template Library (STL) provides a standard library function std::swap() to swap two values.

Syntax of swap()

swap(a, b);

where a and b are the two numbers.

Code Example:

C++
#include <bits/stdc++.h>
using namespace std;

int main(){
    int a = 5, b = 10;

    cout << "Before swapping a = " << a << " , b = " << b << endl;
    // Built-in swap function
    
    swap(a, b);
    
    cout << "After swapping a = " << a << " , b = " << b << endl;
    return 0;
}
Try it on GfG Practice
redirect icon

Output
Before swapping a = 5 , b = 10
After swapping a = 10 , b = 5

Related article:

How to swap two numbers without using a temporary variable?

Comment