C++ Program to Swap Two Numbers using Pointers

The following program illustrates how we can swap two numbers using pointers in C++:

C++
// C++ Program to Swap Two Numbers using Pointers
#include <iostream>  
using namespace std;

// Function to swap two Numbers using pointers
void swap(int* x, int* y) {
    // Store the value pointed to by x in temp
    int temp = *x; 
    // Assign the value pointed by y to the location pointed to by x
    *x = *y;      
    // Assign the value stored in temp to the location pointed to by y
    *y = temp;      
}

int main() {
    // Initialize two numbers x and y
    int x = 5, y = 10;  
    // Print values before swapping
    cout << "Before swapping: x = " << x << ", y = " << y << endl;  

    // Call the swap function, passing the addresses of x and y
    swap(&x, &y);
    
    // Print values after swapping
    cout << "After swapping: x = " << x << ", y = " << y << endl;  
    return 0;  
}

Output
Before swapping: x = 5, y = 10
After swapping: x = 10, y = 5

Time Complexity: O(1)
Auxiliary Space: O(1)

Want to learn about other approaches to swap two numbers? Refer to the following articles:



How to Swap Two Numbers Using Pointers in C++?

Swapping the values of two numbers is a very common operation in programming, which is often used to understand the basics of variables, pointers, and function calls. In this article, we will learn how to swap two numbers using pointers in C++.

Example

Input:
int x=10;
int y=20;

Output:
int x=20;
int y=10;

Similar Reads

Swap Two Numbers Using Pointers in C++

In C++, pointers are variables that store the memory address of another variable. Using pointers the value of variables can be changed directly as we have direct access to the address of the variables. Using this feature of pointers we will swap two numbers. Following is the algorithm we will follow to swap two numbers using pointers in C++:...

C++ Program to Swap Two Numbers using Pointers

The following program illustrates how we can swap two numbers using pointers in C++:...