This is a C++ Program to swap 2 numbers without using a Temp Variable.
We have to write a C++ Program to swap two numbers without using a third variable i.e. the temp variable.
We will write a function swap which takes in two parameters as input, which are the two numbers whose values are to be swapped. We have to do a sequence of operations like addition and subtraction on those numbers so that their values get interchanged after making all these operations.
Input: a = 20, b = 10
Output: a = 10, b = 20
Here is source code of the C++ Program to swap two numbers without using a third variable. The program is successfully compiled and tested using Codeblocks gnu/gcc compiler on windows 10. 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<<"Values before swap :\n";
cout<<"a = "<<a;
cout<<"b = "<<b;
cout << "The two numbers after swapping become :" << endl;
cout << "Value of a : " << a << endl;
cout << "Value of b : " << b << endl;
This C++ Program which swaps the values of two variable without using extra variable. The program calls another function which takes variables as the arguments by reference and manipulates them in order to swap their values inside the function body.
Enter two numbers to be swapped : 2 1 Values before swap : a = 20 b = 10 The two numbers after swapping become : Value of a : 10 Value of b : 20
Sanfoundry Global Education & Learning Series – 1000 C++ Programs.
Here’s the list of Best Reference Books in C++ Programming, Data Structures and Algorithms.