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

«
»

This is a C++ Program to swap 2 numbers without using a Temp Variable.

Problem Description

We have to write a C++ Program to swap two numbers without using a third variable i.e. the temp variable.

Expected Input and Output
Input: a = 20, b = 10

Output: a = 10, b = 20

advertisement
Problem Solution

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.

Program/Source Code

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.

advertisement
  1. /*
  2.  * C++ program to swap two numbers without using a temporary variable
  3.  */
  4. #include<iostream>
  5. using namespace std;
  6. class pro
  7. {
  8. public:
  9.      /* Function for swapping the values */
  10.      void swap(int &a, int &b)
  11.     {
  12.          b = a + b;
  13.          a = b - a;
  14.          b = b - a;
  15.     }
  16. };
  17. int main()
  18. {
  19.     int a, b;
  20.     pro s1;
  21.     cout << "Enter two numbers to be swapped : ";
  22.     cin >> a >> b;
  23.     cout<<"Values before swap :\n";
  24.     cout<<"a = "<<a;
  25.     cout<<endl;
  26.     cout<<"b = "<<b;
  27.     s1.swap(a, b);
  28.     cout<<endl;
  29.     cout << "The two numbers after swapping become :" << endl;
  30.     cout << "Value of a : " << a << endl;
  31.     cout << "Value of b : " << b << endl;
  32. }
Program Explanation

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.

Runtime Test Cases
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.

advertisement

advertisement
advertisement
advertisement
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He is Linux Kernel Developer & SAN Architect and is passionate about competency developments in these areas. He lives in Bangalore and delivers focused training sessions to IT professionals in Linux Kernel, Linux Debugging, Linux Device Drivers, Linux Networking, Linux Storage, Advanced C Programming, SAN Storage Technologies, SCSI Internals & Storage Protocols such as iSCSI & Fiber Channel. Stay connected with him @ LinkedIn