Articles

C++ program to swap two variable using 3rd variable

C++ program to swap two variable using 3rd variable


In this chapter of C++ program tutorial out task is: 

  • Write a C++ program to swap two variable using third variable.

C++ program to swap two variable using 3rd variable

Below is the C++ program to swap two variable using the 3rd variable.

#include<iostream>
using namespace std;
int main()
{
    int a,b,temp=0;
    cout<<"Enter the two variable"<<endl;
    cin>>a>>b;
    cout<<"Value before swapping"<<endl; 
    cout<<"a = "<<a<<"\t"<<"b = "<<b<<endl;
    temp = a;    
    a = b;       
    b = temp;     
    cout<<"Value after swapping"<<endl;
    cout<<"a = "<<a<<"\t"<<"b = "<<b<<endl;
    return 0;
}

OUTPUT :

Enter the two variable
10 20
Value before swapping
a = 10  b = 20
Value after swapping
a = 20  b = 10
 
EXPLANATION :
In the above program:
  • The execution starts from the main function (here int main()).
  • Then a 4 bit each for the three integers are created (assuming the system to be 64 bit).
  • Then the compiler accepts the two variable as the input.
  • Then the value of ("a") is stored in the temporary variable ("temp").
  • Then the previously value of ("a") is replaced by the new value of ("b").
  • Then the previous value of ("b") is replaced by the value of ("temp") which was actually the value of ("a") that was previously stored.
  • Then the number get swapped by the help of third value
  • The program than gives the desired output and terminates in the line "return 0" returning a 0 value.

WORKING :

a = 10 , b = 20

temp = a      ( temp = 10 )

a = b            ( a = 20)

b = temp      ( b = 10)

So, a = 20 and b = 10

 

You can see the above code execution and output in codeblocks IDE:

C++ program to swap two variable using the 3rd variable

 


CPP Programs

Would you like to see your article here on tutorialsinhand. Join Write4Us program by tutorialsinhand.com

About the Author
Sayantan Bose
- šŸ”­ Iā€™m currently working on DS Algo skills - šŸŒ± Iā€™m currently learning web develeopement - šŸ‘Æ Iā€™m looking to collaborate with Oppia - šŸ“« Reach me at https://www.linkedin.com/in/sayantan-bose-14134a1a6/ - šŸ˜„ Pronouns: his/him
Page Views :    Published Date : Jul 24,2020  
Please Share this page

Related Articles

Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!