In this example, we will perform a swapping of two number programs in c++. There are various ways you can swap two numbers:
#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;
}
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.
temp=a
.a=b
.b=temp
.
#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;
}
Before swap a = 10 b = 20 After swap a = 20 b = 10
explanation of above code:
b
i.e b = a + b, (b=10 + 20, now b become b = 30).a
i.e a = b - a (a = 30 - 10, now a = 20).b
i.e b = b - a (b= 30 - 20, now b = 10).
#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.
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;
}
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;
}
Enter Two Numbers: 10 30 Before swap a = 10 b = 30 After swap a = 30 b = 10