C++ Program to Swap Two Numbers
In this example, we will perform a swapping of two number programs in c++. There are various ways you can swap two numbers:
- using temporary variable
- without temporary variable
- using function
- bitwise operator
- using class
swap two number using a temporary variable
#include <iostream>
using namespace std;
int main()
{
int a = 10, b = 20, temp;
cout<<"Before swap a = "<<a<<" b = "<<b<<endl;
temp = a;
a = b;
b = temp;
cout<<"After swap a = "<<a<<" b = "<<b<<endl;
return 0;
}
output
Before swap a = 10 b = 20 After swap a = 20 b = 10
In the above example, we have used three variables a, b, and temp.
- copy the value of the first variable into a temporary variable,
temp=a. - copy the value of the second variable into a first variable,
a=b. - now copy the temporary variable value into the second variable value,
b=temp.
Swap two numbers without using a temporary variable
#include <iostream>
using namespace std;
int main()
{
int a = 10, b = 20;
cout<<"Before swap a = "<<a<<" b = "<<b<<endl;
b = a + b;
a = b - a;
b = b - a;
cout<<"After swap a = "<<a<<" b = "<<b<<endl;
return 0;
}
output
Before swap a = 10 b = 20 After swap a = 20 b = 10
explanation of above code:
- Add a + b and stored it into
bi.e b = a + b, (b=10 + 20, now b become b = 30). - subtract b from a and stored it in variable
ai.e a = b - a (a = 30 - 10, now a = 20). - subtract b from a and stored it in variable
bi.e b = b - a (b= 30 - 20, now b = 10).
swap two number using function
#include <iostream>
using namespace std;
void Swapfun(int &a, int &b) {
int temp = a;
a = b;
b = temp;
}
int main()
{
int a = 10, b = 20;
cout<<"Before swap a = "<<a<<" b = "<<b<<endl;
Swapfun(a, b);
cout<<"After swap a = "<<a<<" b = "<<b<<endl;
return 0;
}
Output is the same as the above program, here we have performed swapping by using function.
Swap number using bitwise operators
The output will same as the above program only difference is here, we have used a bitwise operator for performing the swapping of two numbers.
#include <iostream>
using namespace std;
int main()
{
int a = 10, b = 20;
cout<<"Before swap a = "<<a<<" b = "<<b<<endl;
a = a ^ b;
b = b ^ a;
a = a ^ b;
cout<<"After swap a = "<<a<<" b = "<<b<<endl;
return 0;
}
Swap two numbers using class
In this program, you will take two input numbers from the user and swap the number by using class.
#include<iostream>
using namespace std;
class StudyFame {
private:
int a, b;
public:
void getData();
void swap_number();
void display();
};
void StudyFame::getData() {
cout << "Enter Two Numbers: ";
cin >> a >> b;
}
void StudyFame::swap_number() {
int temp;
temp = a;
a = b;
b = temp;
}
void StudyFame::display() {
cout << "a = " << a << " b = " << b << endl;
}
int main() {
StudyFame s;
s.getData();
cout << "Before swap" << endl;
s.display();
s.swap_number();
cout << "After swap" << endl;
s.display();
return 0;
}
output
Enter Two Numbers: 10 30 Before swap a = 10 b = 30 After swap a = 30 b = 10