Swapping two variables without using third variable. – CSKC
Sign In

Search

Code Learning #CPP#2497    siteicon   siteicon  

Swapping two variables without using third variable.

Swapping of value between two integer variables without using the intermediate third variable.

Learning Objectives

  • Simple way to swap two variables without using the third variable.

Source Code

TC++ #2497

 

Source Code

×

Ask AI About This Code

Default Prompt that is passed along with the code is given below, You can write your own prompt if you so desire.



×

Test CPP

Alternate (?) :

Code Understanding

int a,b,temp; //variable a, b and temp declared. temp will be used later as the intermediate variable.
cout<<“Enter two values a & b:”; cin>>a>>b;
values of a and b are collected here.

cout<<endl<<“You have entered:”<<endl;
cout<<“a=”<<a<<” b=”<<b<<endl;
Here we print the values before swapping.

a=a+b; //First value  a is increased by amount b
b=a-b;      //The increased amount  b is subtracted from a and transferred to b so that effectively b will now contain original value of a.
a=a-b; //The new b which now contains original a is subtracted from a which now contains (a+b) is put to a, which means original b will come to a.

cout<<endl<<“After swapping:”<<endl;
cout<<“a=”<<a<<” b=”<<b<<endl;
Here we print the values after swapping.

Notes

  • This method will be frequently used while using arrays and reversal programs.


Suggested Filename(s): swap-temp.cpp



Share

Created: 11-Jan-2018 22:31 | Updated: 15-Sep-2018 10:52|