Swapping of two numbers in c++

Swapping of two numbers in c++ is c++ program to swap two numbers in c++ without using third variable

In this tutorial, we are going to learn new program which is a simple program and most commonly used in exams or in interviews that is Swap two numbers without using third variable.

What is swapping: Swapping two number means replacing the numbers.

logic to swap two numbers without a third variable

Swapping of two numbers in c++

For swapping number first we have 2 numbers and without using third variable we swap numbers by doing a simple mathematical operation  (sum and subtract )

1. Add first and second number and store addition in the first variable.

a = a + b

2. Subtract first and second number and store it in the second variable.

b = a – b

3. Subtract first and second number and store it in the first variable.

 a = a – b

C++ Program to Swap 2 Numbers Without Using a Temporary Variable

123456789101112131415161718192021222324252627#include <iostream>using namespace std;int main(){ int first,second ;cout<<“Enter first\n”;cin>>first;cout<<“Enter second\n”;cin>>second;cout<<“before swaping\n first = “<<first<<“\n second = “<<second<<“\n”; first = first + second; second = first – second; first = first – second;cout<<“after swaping\n first = “<<first<<“\n second = “<<second<<“\n”;    return 0;}

Output :

swap two numbers in cpp
swap two numbers in cpp

Explanation:

1. First Here we initialized the first and second variable.

first —> for storing 1st number

second  –>for storing the second number

2. Now here goes the logic(let us take first = 10 and second=20)

first = first + second ,  Therefore, first =10+20 =30

second = first – second , Therefore  second = 30 – 20 =10

first = first – second,  Therefore first =30 – 10 = 20

3. Now the values of first and second are 20 and 10

4. The values of first and second are printed.