Algorithm Swap Two Number: 

Here we will see a program to swap two numbers using a temporary third variable. The steps are as follows:
1. User is asked to enter the value of first and second number. The input values are stored in first(num1) and second(num2) variable.
2. Assigning the value of first variable to the third variable.
3. Assigning the value of second variable to the first variable.
4. Assigning the value of third variable to the second variable.

Source Code: 


#include <iostream>
using namespace std;

int main()
{
    int num1, num2, temp;
    cout<<"Enter 1st Number: "; 
    cin>>num1;
    cout<<"Enter 2nd Number: "; 
    cin>>num2;

    //displaying numbers before swapping
    cout<<"Before Swapping: First Number: "<<num1<<" Second Number: "<<num2;

    //swapping
    temp=num1;
    num1=num2;
    num2=temp;

    //displaying numbers after swapping
    cout<<"\nAfter Swapping: First Number: "<<num1<<" Second Number: "<<num2;
    return 0;
}


Program to Swap Two Numbers Using Third Variable

The program to swap two numbers using a temp variable is as follows.

Example

#include <iostream >
using namespace std;
int main() {    
   int a = 10, b = 5, temp;
   temp = a;
   a = b;
   b = temp;
   cout<<"Value of a is "<<a<<endl;
   cout<<"Value of b is "<<b;
   return 0;
}

Output

Value of a is 5
Value of b is 10
In the above program, there are two variables a and b that store the two numbers. First, the value of a is stored in temp. Then, the value of b is stored in a. Lastly, the value of temp is stored in b. After this, the values in a and b are swapped.
temp = a;
a = b;
b = temp;  
Then the values of a and b are displayed.
cout<<"Value of a is "<<a<<endl;
cout<<"Value of b is "<<b;

Program to Swap Two Numbers Without Using a Third Variable

The program to swap two numbers without using a third variable is as follows −

Example

#include <iostream>
using namespace std;
int main() {    
   int a = 10, b = 5;
   a = a+b;  
   b = a-b;  
   a = a-b;  
   cout<<"Value of a is "<<a<<endl;
   cout<<"Value of b is "<<b;
   return 0;
}

Output

Value of a is 5
Value of b is 10
In the above program, first the sum of a and b is stored in a. Then, the difference of a and b is stored in b. Finally, the difference of a and b is stored in b. At the end of this, the values in a and b are swapped.
a = a+b;  
b = a-b;  
a = a-b;  
Then the values of a and b are displayed.
cout<<"Value of a is "<<a<<endl;
cout<<"Value of b is "<<b;

Post a Comment

 
Top