Header Ads Widget

Ticker

6/recent/ticker-posts

C++ Program to swap two numbers without third variable by Digitalise Data

C++ Program to swap two numbers without third variable by Digitalise Data

 

C++ Program to swap two numbers without third variable

We can swap two numbers without using third variable. There are two common ways to swap two numbers without using third variable:

  1. By + and -
  2. By * and /


Program 1: Using * and /

Let's see a simple C++ example to swap two numbers without using third variable.

  1.  #include <iostream.h> 
  2. #include <conio.h>   
  3. void main()  
  4. {  
  5. int a=5, b=10;      
  6. cout<<"Before swap a= "<<a<<" b= "<<b<<endl;      
  7. a=a*b; //a=50 (5*10)    
  8. b=a/b; //b=5 (50/10)    
  9. a=a/b; //a=10 (50/5)    
  10. cout<<"After swap a= "<<a<<" b= "<<b<<endl;      
  11. getch();  
  12. }  

Output:

Before swap a= 5 b= 10     
After swap a= 10 b= 


Program 2: Using + and -

Let's see another example to swap two numbers using + and -.

  1. #include <iostream.h> 
  2. #include <conio.h>  
  3. void main()  
  4. {  
  5. int a=5, b=10;      
  6. cout<<"Before swap a= "<<a<<" b= "<<b<<endl;      
  7. a=a+b; //a=15 (5+10)    
  8. b=a-b; //b=5 (15-10)    
  9. a=a-b; //a=10 (15-5)    
  10. cout<<"After swap a= "<<a<<" b= "<<b<<endl;      
  11. getch ();  
  12. }  

Output:

Before swap a= 5 b= 10  
 After swap a= 10 b= 5

Post a Comment

0 Comments