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");

}


Second way, by using multiplication-division 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");

}


Feel free to ask anything!




Comments

Popular posts from this blog

Community Detection Algorithm (Leiden Algorithm in Python)

Stack and Queues

How To Earn Money Online