How to swap two numbers without using third variable in C++

In this tutorial, we will learn how to swap two numbers (without using third variable) in C++ in a very easy and interesting way. While we are doing programming at a professional level there will be a requirement of using minimum memory to reduce various expenses.

If you are searching for a similar situation then you are at the right place. This is a very basic method which you can apply in any program where you need to exchange the values of two variables.

This method will be applicable in other programming languages like python, java and many more.

Swapping two numbers without using third variable

Methodology

Suppose there are two variables viz. variable1 and variable2. Now the process of swapping is performed in the following steps.

  • variable1=varialble1+variable2
  • variable2=variable1-variable2
  • variable1=variable1-variable2

You can understand the method by referring to the detailed diagram explaining this method from here.



Swap two numbers without using third variable in C++

#include<iostream.h>			//for input and output
#include<conio.h>
int main(){
  clrscr();			//clear the screen

  int var1,var2;
  cout<<"Enter value of first variable: ";
  cin>>var1;
  cout<<"Enter value of second variable: ";
  cin>>var2;
  cout<<"Values before swapping-"<<endl;
  cout<<"Variable 1: "<<var1<<endl;
  cout<<"Variable 2: "<<var2<<endl;

  var1=var1+var2;			//Swapping
  var2=var1-var2;
  var1=var1-var2;

  cout<<"Values after swapping-"<<endl;
  cout<<"Variable 1: "<<var1<<endl;
  cout<<"Variable 2: "<<var2<<endl;

  getch();
  return(0);
}

I have used Turbo C++ v 4.0 for the whole working of the program. Anyways this code will work fine with any C++ compiler without any issues.

Working

The program firstly declares two variables viz. var1 and var2. The values are taken for these variables are taken by the user. Then the values of the variables will print on the screen before swapping. The swapping is then taken place and finally the values are printed on screen.

Output example

Enter value of first variable: 34
Enter value of second variable: 53
Values before swapping-
Variable 1:  34
Variable 2:  53
Values after swapping-
Variable 1:  53
Variable 2:  34

Hope you have understood the method. Now you can apply this method anywhere you need and this will help you minimize the memory consumption when used in large programs.

Feel free to drop your queries in the comment section below.

Also read:-

Leave a Reply

Your email address will not be published. Required fields are marked *