C++ Programs Examples
How to swap two variables in c++?
We can swap two variables very easily in c++. There are two methods of swap.
First method: By using a temporary variable.
Second method: Without using temporary variable.
Lets start with the first method. We use a third variable which is called temporary variable and represented as temp.
The code is very simple and is given below:
#include<iostream>
using namespace std;
void main()
{
int a = 5, b = 10;
cout << "a= " << a << " " << "b= " << b << endl;
int temp = a;
a = b;
b = temp;
cout << "After swap:" << endl;
cout << "a= " << a << " " << "b= " << b << endl;
system("pause");
}
In second method, we do not use any temporary variable. It has further two ways.
First way, by using addition-subtraction approach.
Code is given below:
#include<iostream>
using namespace std;
void main()
{
int a = 5, b = 10;
cout << "a= " << a << " " << "b= " << b << endl;
a=a+b;
b=a-b;
a=a-b;
cout << "After swap:" << endl;
cout << "a= " << a << " " << "b= " << b << endl;
system("pause");
}
Code is given below:
#include<iostream>
using namespace std;
void main()
{
int a = 5, b = 10;
cout << "a= " << a << " " << "b= " << b << endl;
a=a*b;
b=a/b;
a=a/b;
cout << "After swap:" << endl;
cout << "a= " << a << " " << "b= " << b << endl;
system("pause");
}
Comments
Post a Comment
Feel free to comment or ask something related to games.