How to swap two numbers using pointer in C++

How to swap two numbers using pointers in C++:

In this post, we will learn how to swap or exchange two numbers using pointers in C++. Pointers are used to keep the memory address of variables. We will write one function that will take two pointers of two integer variables and swap these integer variables by using the pointers.

Passing pointers to a function is a better way to exchange or change any value because we are passing the memory address of a variable. If we change anything that is stored in that memory address, we don’t have to assign any other value to the variable, it will be changed immediately.

Algorithm to use in the program:

We will use the following algorithm:

  • Take the numbers as inputs from the user. Store these numbers in two different integer variables.
  • Pass the pointers of these variables to a different function.
  • Inside the function, exchange the content of these variables using a third variable. We need to follow the following steps to swap two numbers:
    • Assign the value of the second variable to the third variable.
    • Assign the value of the first variable to the second variable.
    • Assign the value of the third variable to the first variable.
  • With these three steps, the values of the variables will be swapped.
  • Once done, print the numbers again to the user.

C++ program to swap two numbers with pointers:

Below is the complete C++ program that swaps two user input numbers using pointers:

#include <iostream>
using namespace std;

void swap(int *first, int *second)
{
    int temp;

    temp = *first;
    *first = *second;
    *second = temp;
}

int main()
{
    int a, b;

    cout << "Enter the numbers : " << endl;
    cin >> a;
    cin >> b;

    cout << "Before swap, a = " << a << ", b = " << b << endl;
    swap(&a, &b);
    cout << "After swap, a = " << a << ", b = " << b << endl;
}

Download it on Github

Here,

  • a and b are two integer variables.
  • We are taking the numbers as inputs from the user and these values are assigned to the variables a and b respectively.
  • The method swap is used to swap two numbers using pointers. It takes two integer pointers as the parameters and swaps the values stored in the addresses pointed by these pointers.
    • The variable temp is used as a temporary variable.
    • It first assigns the value pointed by the variable first to the temp variable.
    • Then it assigns the value pointed by the second variable to the first variable.
    • Finally, it assigns the value pointed by the temp variable to the second variable. With this step, both numbers are swapped.
  • This program is printing the values of the integers before and after the numbers are swapped.

C++ example to swap numbers using pointers

It will print outputs as below:

Enter the numbers : 
12
13
Before swap, a = 12, b = 13
After swap, a = 13, b = 12

You might also like: