Here is source code of the C++ program which swaps the values of two variable without using extra variable. The C++ program is successfully compiled and run on a Linux system. The program output is also shown below.
* C++ program to swap two numbers without using a temporary variable
using namespace std;
/* Function for swapping the values */
void swap(int &a, int &b)
b = a + b;
a = b - a;
b = b - a;
int a, b;
cout << "Enter two numbers to be swapped : ";
cin >> a >> b;
cout << "The two numbers after swapping become :" << endl;
cout << "Value of a : " << a << endl;
cout << "Value of b : " << b << endl;
$ g++ main.cpp $ ./a.out Enter two numbers to be swapped : 3 4 The two numbers after swapping become : Value of a : 4 Value of b : 3
Sanfoundry Global Education & Learning Series – 1000 C++ Programs.
If you liked this C++ Program, kindly share, recommend or like below!