How to swap two numbers using pointers in C++
In this tutorial, we are going to learn how to swap two numbers in C++ using pointers.
Before we understand the implementation let’s see what are pointers and its example along with the syntax. We know that pointers work as a variable whose value defines the address of another variable. For example – An integer variable will always store an integer value but an integer pointer will store the address of the integer variable.
Syntax: data_type*var_name.
Implementation Algorithm
First, we will enter two user numbers and store their values in x and y. Next, we will be declaring three-pointers to store address i.e. num_1,num_2, and temp. Then we will implement a swapping procedure that goes like this.
- Set value of num_1 to temp.
- Set value of num_2 to num_1.
- Set temp value to num_2.
Now swapped numbers will be displayed using pointers num_1 and num_2.
Follow the comments in the code for better understanding.
C++ code: Swap two numbers using pointers
#include <iostream> using namespace std; int main() { int x,y; // Input any two numbers from the user. cout << "Enter the numbers:\n"; cin>>x>>y; int *num_1,*num_2,temp; //Declaring pointers num_1=&x; // Declaring address num_2=&y; temp=*num_1; //Swap procedure starts *num_1=*num_2; *num_2=temp; cout<<"Numbers after swapping:"; //Numbers will be displayed after swap cout<<"\nfirst number="<<x; //First number after swap cout<<"\nsecond number="<<y; // Second number after swap return 0; }
Input:
Enter the numbers: 24 58
Output:
Numbers after swapping: first number=58 second number=24
Leave a Reply