Search

Swap two numbers without using third variable in C++

1st way – Swap using a third variable which is very common & ordiary

In this tutorial, we are going to see 2nd way to swapping without using third variable

Program to Swap two numbers without using third variable

Using + and –

• #include <iostream>

• using namespace std;

• int main()

• {

• int a=5, b=10;

• cout<<"Before swap a= "<<a<<" b= "<<b<<endl;

• a=a+b; //a=15 (5+10)

• b=a-b; //b=5 (15-10)

• a=a-b; //a=10 (15-5)

• cout<<"After swap a= "<<a<<" b= "<<b<<endl;

• return 0;

• }

Output –

Before swap a= 5 b= 10

After swap a= 10 b= 5

Using / and *

• #include <iostream>

• using namespace std;

• int main()

• {

• int a=5, b=10;

• cout<<"Before swap a= "<<a<<" b= "<<b<<endl;

• a=a*b; //a=50 (5*10)

• b=a/b; //b=5 (50/10)

• a=a/b; //a=10 (50/5)

• cout<<"After swap a= "<<a<<" b= "<<b<<endl;

• return 0;

• }

Output –

Before swap a= 5 b= 10

After swap a= 10 b= 5

For Video Tutorials Subscribe our Youtube Channel

---------------------------------------------------------------------------------------------------------------------------

Previous Page Next Page

Any Doubt ? Feel free to write a comment

Mandatory to join Telegram group for regular job updates

Mandatory to join whatsapp group for regular job updates

Other C++ Programs

Tags:

Related Posts

See All

Number to Character Conversion in C++

Program to implement Number to Character Conversion in C++ Firstly see what we are going to do ? Like this 0 - zero 1 – one 2 – two 3 – three 4 – four 5 – five 6 – six 7 – seven 8 – eight 9 – nine How

Factorial of a number in C++

In this tutorial we are going to see how to find a factorial of number using C++ program Firstly let’s see a example to understand it better n! = n + (n-1) + (n-2) ! n>=1 3! = 3 *2*1 = 6 Program to fi

Fibonacci Triangle in C++

Program to implement Fibonacci Triangle in C++ #include <iostream> using namespace std; int main() { int a=0,b=1,i,c,n,j; cout<<"Enter the limit: "; cin>>n; for(i=1; i<=n; i++) { a=0; b=1; cout<<b<<"\