C++ Program To Swap Two Numbers Without Third Variable - C++ Programming Tutorial
C++ Course / C++ Programs / C++ Program To Swap Two Numbers Without Third Variable

C++ Program To Swap Two Numbers Without Third Variable

BLUF: Mastering C++ Program To Swap Two Numbers Without Third Variable is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: C++ Program To Swap Two Numbers Without Third Variable

C++ is renowned for its efficiency. Learn how C++ Program To Swap Two Numbers Without Third Variable enables low-level control and high-performance computing in the tutorial below.

We have the ability to exchange the values of two numbers without the need for a third variable. Two popular methods for swapping two numbers without a third variable are:

  • Using addition and subtraction
  • Utilizing multiplication and division
  • Program 1: Using * and /

Let's examine a basic C++ illustration demonstrating how to interchange two values without the need for a third variable.

Example

Example

#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:

Output

Before swap a= 5 b= 10     

After swap a= 10 b= 5

Program 2: Using + and -

Let's explore another instance of exchanging two numbers by utilizing the addition and subtraction operations.

Example

Example

#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:

Output

Before swap a= 5 b= 10  

 After swap a= 10 b= 5

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience