Swap Numbers Without Using a Temporary Variable

We can also swap numbers without using the temporary variable. Unlike the previous method, we use some mathematical operations to swap the values.

Algorithm

  1. Assign to b the sum of a and b i.e. b = a + b.
  2. Assign to a difference of b and a i.e. a = b – a.
  3. Assign to b the difference of b and a i.e. b = b – a.

C++ Program to Swap Two Numbers Without Using a Temporary Variable.

C++




// C++ program to swap two
// numbers without using 3rd
// variable
#include <bits/stdc++.h>
using namespace std;
 
// Driver code
int main()
{
    int a = 2, b = 3;
 
    cout << "Before swapping a = " << a << " , b = " << b
         << endl;
 
    // applying algorithm
    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

Complexity Analysis

  • Time Complexity: O(1), as only constant time operations are done.
  • Space Complexity: O(1), as no extra space has been used.

C++ Program to Swap Two Numbers

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.

Similar Reads

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 algorithm shows how to use the temporary variable to swap values....

2. Swap Numbers Without Using a Temporary Variable

...

3. Swap Two Numbers Using Inbuilt Function

We can also swap numbers without using the temporary variable. Unlike the previous method, we use some mathematical operations to swap the values....