Swap values of two variables in C++

In this tutorial, we will see how to swap the values of two variables in C++. We will see swapping by using a third variable or without using a third variable. Hope you will like this tutorial. Let’s get started.

Swap two values in C++

Suppose we are given two variables a and b we want to swap the values present in them. Firstly we will see this by using the third variable which is the temp variable.

  1. Store value of the variable a in temp.
  2. Then store the value of variable b in a.
  3. Now again store the value of variable temp in b.

Let’s see with Code Example:

#include <iostream>
using namespace std;
  
int main()
{
    int a = 50;
    int b = 30;
    cout << "Value of a before Swap: " << a << endl;
    cout << "Value of b before Swap: " << b << endl;
  
    // swap values of the variables
    int temp = a;
    a = b;
    b = temp;

    cout << "Value of a after swap: " << a << endl;
    cout << "Value of b after swap: " << b << endl;
    return 0;
}
OUTPUT:
Value of a before Swap: 50
Value of b before Swap: 30
Value of a after swap: 30
Value of b after swap: 50

Instead of using the third variable temp while swapping, one can use the built-in swap() function in C++. Under STL we have the std::swap() function which helps in swapping two variables without using a third variable.

Let’s understand with code.

#include <bits/stdc++.h>
using namespace std; 
int main() { 
    int a = 50; 
    int b = 30; 
    cout << "Value of a before Swap: " << a << endl; 
    cout << "Value of b before Swap: " << b << endl; 
    
    // swap values of the variables 
    swap(a,b); // std::swap() function
    cout << "Value of a after swap: " << a << endl; 
    cout << "Value of b after swap: " << b << endl; 
    return 0; 
    
}
OUTPUT:
Value of a before Swap: 50
Value of b before Swap: 30
Value of a after swap: 30
Value of b after swap: 50

Using these two methods one can swap two variables’ values in C++. Hope you liked this tutorial. Keep learning!!

Also Read: C++ Null Pointers with examples || MultiKeyMap in C++

Leave a Reply

Your email address will not be published.