Thursday, 22 June 2017 12:51

## C++ Program to swap two numbers without third variable

Written by
Rate this item

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>
2. using namespace std;
3. int 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. return 0;
12. }

Output:

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

## Program 2: Using + and -

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

1. #include <iostream>
2. using namespace std;
3. int 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. return 0;
12. }

Output:

```Before swap a= 5 b= 10
After swap a= 10 b= 5``` ### Anish Sir

"I am delighted once again to pen the welcome note to the Tosh!Yas Technologies ."

Call +91 74 88 34 7779  | Email : anishsingh@live.com

### Latest from Anish Sir

More in this category: « C++ Program to reverse number