Open In App

Swap Two Numbers Without Third Variable in C++

Last Updated : 14 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, swapping two numbers means we need to exchange the value of two numbers. In this article, we will learn how to swap two numbers without using the third variable in C++.

Example

Input: 
a=10
b=20

Output:
After swapping:
a=20
b=10

Swap Two Numbers Without Using a Third Variable

In C++ we can swap two numbers without using a temporary variable by using simple addition and subtraction arithmetic trick as shown.

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

The below program shows how we can swap two numbers without using a temporary variable.

C++




// C++ program to swap two numbers without using temporary
// variable
  
#include <iostream>
using namespace std;
  
int main()
{
    // numbers to be swapped
    int a = 5, b = 10;
    int x = 50, y = 100;
  
    cout << "Before swapping: x = " << x << ", y = " << y
         << endl;
  
    // performing swap using addition substraction method
    x = x + y;
    y = x - y;
    x = x - y;
    // print values after swapping
    cout << "After swapping: x = " << x << ", y = " << y
         << endl
         << endl;
  
    return 0;
}


Output

Before swapping: x = 50, y = 100
After swapping: x = 100, y = 50

Time Complexity: O(1)
Auxiliary Space: O(1)


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads