Program to swap two variables without using third or temp variable

Program to swap two variables without using third or temp variable
Di Posting Oleh : Simple Learning
Kategori : swap with two variables swap without temp swap without third variable

Program Logic Steps:
  • Store sum of both in var1.
  • Subtract var2 from var1 and store it in var2 (now var2 has value of var1) .
  •     Subtract var2 from var1 and store it in var1 (now var1 has    value of var2).
  •  
Image View of Code

C++ code to swap two variables without using third variable:

#include<iostream>

using namespace std;

int main()

{

int var1, var2;

 cout<<"Enter value for first integer:  ";

 cin>>var1;

 cout<<"Enter value for second integer:  ";

 cin>>var2;

 cout<<" Values Before swapping:  "<<endl;

 cout<<"First Integer ="<<var1<<endl;

 cout<<"Second Interger ="<<var2<<endl;

              var1=var1+var2;

              var2=var1-var2;

              var1=var1-var2;

 cout<<" Values After swapping:  "<<endl;

 cout<<"First Integer ="<<var1<<endl;

 cout<<"Second Interger ="<<var2<<endl;

    return 0;

}



Sample Output



 Image view of code:

0 Response to "Program to swap two variables without using third or temp variable"

Post a Comment