C++ Program to swap two numbers without third variable.
C++ Program to Swap Two Numbers.

This Programs contains three different way to swap numbers in C++ programming.

 The first program uses swap two numbers without third variable using * and /, whereas the second program swap two numbers without third variable using + and - and third C++ program uses temporary variable to swap numbers.

swap numbers in C++ programming. code c++


C++ program uses swap two numbers without third variable using * and / .

SOURCE CODE:

 #include <iostream>  
/*  iostream provides basic
input and output services for C++ programs */
using namespace std;  
int main()
// Th execution of program start with the main function   
{  
int a=5, b=10;  
//Initialization is the process of assign the value to a variable      
cout<<"Number Before swap a= "<<a<<" b= "<<b<<endl;      
a=a*b; //(5*10)  a=50  
b=a/b; //(50/10) b=5    
a=a/b; //(50/5)  a=10
// cout is used to display the same statement in the output.   
cout<<"Number After swap a= "<<a<<" b= "<<b<<endl;      
return 0;  
}  


C++ program swap two numbers without third variable using + and - .


SOURCE CODE:

#include <iostream>
/*  iostream provides basic
input and output services for C++ programs */  
using namespace std;  
int main() 
// Th execution of program start with the main function  
{  
int a=5, b=10; 
//Initialization is the process of assign the value to a variable       
cout<<"Number Before swap a= "<<a<<" b= "<<b<<endl;   
// cout is used to display the same statement in the output.       
a=a+b; //(5+10)  a=15  
b=a-b; //(15-10)  b=5  
a=a-b; //(15-5)  a=10   
cout<<"Number After swap a= "<<a<<" b= "<<b<<endl;      
return 0;  
}  


C++ program uses temporary variable to swap numbers.

SOURCE CODE:

#include <iostream>
/*  iostream provides basic
input and output services for C++ programs */
using namespace std;
int main()
// Th execution of program start with the main function 
{
    int a = 5, b = 10, temp;
//Variable Declarations specify the type followed by the name
//Initialization is the process of assign the value to a variable  
    cout << "Number Before swapping." << endl;
    cout << "a = " << a << ", b = " << b << endl;
    temp = a; // temp=5
     
    a = b; // a = 10
    
    b = temp; // b = 10
    cout << "\nNumber After swapping." << endl;
    cout << "a = " << a << ", b = " << b << endl;
    return 0;
}