WAP to swap two Number using Pointer
Objective
Write a C++ program to swap two numbers using Pointers.
Algorithm / Approach
- Declare variables
x,yand pointersa,b. - Point
atoxandbtoy. - Swap the data stored at those memory addresses:
temp = *b; *b = *a; *a = temp;.
main.cpp
#include<iostream>
using namespace std;
int main( ) {
int x, y, *a, *b, temp;
cout<<"Enter the value of X and Y : ";
cin>>x>>y;
cout<<"Before Swapping\n";
cout<<"X = "<< x<<"\nY = " << y;
cout<< endl;
a = & x;
b = & y;
temp = *b;
*b = *a;
*a = temp;
cout<<"After Swapping\n";
cout<<"X = "<< x<<"\nY = " << y;
return 0;
}
Expected Output
Enter the value of X and Y : 10 20 Before Swapping X = 10 Y = 20 After Swapping X = 20 Y = 10
Explanation of the Program
- Unlike the earlier function that failed to swap variables because it only had "copies", pointers allow us to reach directly into memory and manipulate the original variables.
- By dereferencing the pointers (
*aand*b), we are literally changing the data sitting in the memory spaces ofxandy.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)