![]() |
VOOZH | about |
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;
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++:
- Declare a function swap that takes two integer pointers x and y as parameters.
- Use a temporary variable temp to store the value of x.
- temp=*x;
- Store the value of y in x by dereferncing the pointers.
- *x=*y
- Store the value of temp in y.
- *y=temp;
- Call the swap function by passing the address of x and y.
If you are not familiar with the concept of dereferencing, you can read the following article --> C++ Dereferencing
The following program illustrates how we can swap two numbers using pointers in C++:
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: