C++ Program to swap two numbers using pointers


In this program, You will learn how to swap two numbers using pointers in C++.


Numbers is: 10 20

After swap: 20 10

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

#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;
}

Output:

Enter two numbers:10 20
After swap x is:20
After swap y is:10