12th Class NCERT Solution Download Click Here!

X




Sunday, 13 March 2016

Write a program to swap the values of two variables.

#include<iostream>
using namespace std;

int main()
{
 int a,b,temp;
 cout<<"\nEnter two numbers : ";
 cin>>a>>b;
 temp=a; 
 a=b;
 b=temp;
 cout<<"\nAfter swapping numbers are : ";
 cout<<a<<" "<<b;

 return 0;
}

OUTPUT:

Enter two numbers : 78 6
After swapping numbers are : 6 78

Hint: We are just using a simple trick , think you(take variable a ) and your friend (variable b) have bags in your hands , now you want to exchange your bags. For doing this you ask your another friend ( flag ). You give your bag to your 3rd ( variable flag ) friend and take bag from your 2nd friend (variable b) . Now your 2nd friend take bag from your 3rd friend . This way you exchanged your bags using 3rd friend. Same concept is used in this program.

No comments:

Post a Comment