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++:
Algorithm
- 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
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;