Skip to main content

ProwessApps

Learn · Practice · Excel

WAP to swap two Number using Pointer

C++ Code Example — Function Programs

ADVERTISEMENT

WAP to swap two Number using Pointer

Objective

Write a C++ program to swap two numbers using Pointers.

Algorithm / Approach

  1. Declare variables x, y and pointers a, b.
  2. Point a to x and b to y.
  3. 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 (*a and *b), we are literally changing the data sitting in the memory spaces of x and y.

Complexity

Time Complexity O(1)
Space Complexity O(1)
ADVERTISEMENT