Program to swap two numbers using pointer

0 Suresh Chand April 2, 2021

In this example, You will learn to swap two numbers using pointer. Here, We will use 5 variables. 3 of them are integer variables and 2 of them are pointer variables.

Before going through this example, You must have knowledge in following topics

Here, First we will take 2 input from user and stored in integer variables.

We will assign address of that variables to the pointer variables as like

a = &x;
b = &y;

Then we will assign pointer of a variable to temp variable.

temp = *a;

Again, We will assign pointer variable of b to pointer variable of a.

*a = *b

Finally, We will assign value of temp variable to pointer variable of a.

*b = temp;

On this way, Our program works and two numbers are swap using pointers.

Lets look an code for detail explanation.

Code: swap two numbers using pointer

#include<iostream>
using namespace std;

int main() {

    int x, y, temp;
    int *a, *b;

    cout << "Enter two numbers:";
    cin >> x>>y;

    a = &x;
    b = &y;

    temp = *a;
    *a = *b;
    *b = temp;

    cout << "After swap x is:" << x;
    cout << "\nAfter swap y is:" << y;

    return 0;
}

The output of above code is

Program to swap two numbers using pointers
Output
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Join Our Newsletter Now

Get the latest tutorials, examples and projects updates.

!

Ads

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.

Disable Ad Block

Want Same System