In the above C++ program to swap two numbers without using a third variable, we have used arithmetic logic to get the desired result.
#include <iostream>
using namespace std;
int main()
{
cout << "\n\n Swap two numbers without using third variable:\n";
cout << "---------------------------------------------------\n";
int num1, num2, temp;
cout << " Input first number : ";
cin >> num1 ;
cout << " Input second number : ";
cin >> num2;
num2=num2+num1;
num1=num2-num1;
num2=num2-num1;
cout << " After swapping the first number is : "<< num1 <<"\n" ;
cout << " After swapping the second number is : "<< num2 <<"\n\n" ;
}
Sample Output: Input first number : 45 Input second number : 76 After swapping the first number is : 76 After swapping the second number is : 45