C++ Program to swap two numbers without using temporary variable

Today we are going to write a C++ program to swap two numbers without using  any temporary variable, let’s start. There are many ways to swap two numbers without using a Temporary variable.

Here I’ve discussed two methods:

  1. Using ‘+’ and ‘-‘ operators.
  2. Using Bitwise XOR ‘^’.

There is another way to swap using call by reference method.

So here’s the First Program:

C++ Program to Swap two numbers using  ‘+’ ‘-‘ operators:

#include<iostream>
using namespace std;

int main()
{
   int a, b;

   cout<<"Enter two integers to swap\n";
   cout<<"Enter a= ";
   cin>>a;
   cout<<"Enter b= ";
   cin>>b;

   a = a + b;   \\ ex. a=5,b=6  so,  here a = 5+6 = 11
   b = a - b;   \\  b= a-b i.e. b = 11-6 = 5
   a = a - b;   \\  a= a-b i.e. a = 11-5 = 6

   cout<<"\nAfter Swapping\n";
   cout<<"a = "<<a<<"\nb = "<<b;
   return 0;
}

 

OUTPUT:

c++ program to swap two numbers

 

Now let’s discuss the second method i.e. using the Bitwise XOR ‘^’.

 

C++ Program to Swap two numbers using Bitwise XOR ‘^’

#include<iostream>
using namespace std;

int main()
{
   int a, b;

   cout<<"Enter two integers to swap\n";
   cout<<"Enter a= ";
   cin>>a;
   cout<<"Enter b= ";
   cin>>b;

   a = a ^ b;
   b = a ^ b;
   a = a ^ b;

   cout<<"\nAfter Swapping\n";
   cout<<"a = "<<a<<"\nb = "<<b;
   return 0;
}

 

OUTPUT:

c++ program to swap two numbers

There many other ways in which we can do this like using call by reference etc. I’ve discussed the simplest one hope you like it, please comment if you have any other methods or any improvement for the above codes. Thank you.

4 thoughts on “C++ Program to swap two numbers without using temporary variable”

Leave a Comment