# Swap two numbers using pointers

Written by

Garvit Gulati

### Introduction to pointers:

Pointers are a data-type offered by C++ to store the memory address of other datatypes.

Syntax:

``````<data_type> pointer_name;
``````

Here data-type is the data-type of the variable whose value a pointer will hold.

*’ asteric operator is used to access the value whose address a pointer is storing.

Example,

``````int *a;

int b=12;

cout<<a<<”\n”;

cout<<*a;
``````

In this program, the third line will print the address of b in memory whereas the fourth line will print the value of b(I.e.12). Read More.

### Approaching the given problem:

To swap two numbers using pointers, we will first store the values in normal variables and declare two pointers to them. Then we will declare a pointer temp. Then, with the help of ’*’ operator, we will store the value of first pointer in temp. Then we will change the value in first pointer equal to the value in second pointer and then we set the value of second pointer equal to the value in temp.

### Algorithm:

1. Prompt the user to input two numbers and store them in variables a and b.
2. Declare three pointers: x, y, and temp.
3. Assign the address of a to x and the address of b to y.
4. Swap the values of a and b by assigning the value of a to temp, the value of b to a, and the value of temp to b.
5. Print the values of a and b after the swap using the pointers x and y.

Code:

``````#include <iostream>

using namespace std;

int main()
{
int a, b;
cout << "Enter two numbers\n"; //taking input from the user
cin >> a >> b;
int *x, *y, temp;
x = &a; //setting pointers to store the address of
y = &b; // variables containing entered values
temp = *x; //swapping
*x = *y;
*y = temp;
cout << "Numbers after swapping:"; //displaying the numbers after swapping
cout << "\nfirst number=" << a;
cout << "\nsecond number=" << b;
return 0;
}

``````

Output:

``````Enter two numbers:
14 16

Number after swapping:
first number=16
second number=14
``````