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.
Input: a = 20, b = 10
Output: a = 10, b = 20
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.
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
*/
#include<iostream>
using namespace std;
class pro
{
public:
/* Function for swapping the values */
void swap(int &a, int &b)
{
b = a + b;
a = b - a;
b = b - a;
}
};
int main()
{
int a, b;
pro s1;
cout << "Enter two numbers to be swapped : ";
cin >> a >> b;
cout<<"Values before swap :\n";
cout<<"a = "<<a;
cout<<endl;
cout<<"b = "<<b;
s1.swap(a, b);
cout<<endl;
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 Books in C++ Programming, Data Structures and Algorithms.
- Check Programming Books
- Check C++ Books
- Apply for Computer Science Internship
- Apply for C++ Internship
- Check Computer Science Books