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

Search

Code Learning #CPP#2493    siteicon   siteicon  

Swapping two variables using temporary third variable.

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

Learning Objectives

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

Source Code

TC++ #2493

 

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.

temp=a; //First value  a is shifted to a temporary variable temp
a=b;      //Second value b is shifted to first value a as first value is already save in temp
b=temp; //First value a which is saved in temp variable is brought  into second value b

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.
  • This method can easily be used for any data type; char, int, long, float, double etc.

Common Errors

  • Erroneously some students shift b to a first and then move a to b. This will obviously destroy initial value of a. Watch -a=b; temp=a; b=temp; //This is incorrect
    temp=a; a=b; b=temp; //This is correct


Suggested Filename(s): swap-temp.cpp



Share

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