Navigation Bar

C++ Program to swap two variables without using third variable or temporary 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;

}

No comments:

Post a Comment