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++

Run it Now
#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 << "\nAfter 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