How to swap two numbers using pointers in C++

In this article, we are going to learn How to swap two numbers using pointers in C++. We will learn how to swap two numbers in C++ using the pointers.


#include <iostream>
using namespace std;

void swapNumbers(int *num1, int *num2);

int main() 
{
   int NumOne, NumTwo;
 
   cout<<"\nPlease enter the First Number to Swap : ";
   cin>>NumOne;
   cout<<"\nPlease enter the Second Number to Swap : ";
   cin>>NumTwo;
 
   //Passing the addresses of num1 and num2
   swapNumbers(&NumOne, &NumTwo);
 
  
   cout<<"\nNumbers after Swapping  : ";
   cout<<"\n First number : "<< NumOne;
   cout<<"\n Second number: "<<NumTwo;
 
   return 0;
}

void swapNumbers(int *num1, int *num2) 
{
   int temp;
   
   temp = *num1;
   
   *num1 = *num2;
 
   *num2 = temp;
}

Output

Please enter the First Number to Swap : 6

Please enter the Second Number to Swap : 8

Numbers after Swapping  : 
 First number : 8
 Second number: 6