Signup/Sign In

C++ Program For Swapping Two Number In Function Using Pointer

In this program, we will learn how to swap two numbers using pointers in C++.

Swapping Two Number In Function Using Pointer In C++

The simplest and probably most widely used method to swap two variables is to use a third temporary variable:

temp := x
x:= y
y:= temp

Before proceeding to the implementation of the program, let's understand the approach. Here, instead of using the simple variables, we will be dealing in terms of the pointers.

#include <iostream>
using namespace std;
 
//Swap function to swap 2 numbers
void swap(int *num1, int *num2) {
   int temp;
   //Copy the value of num1 to some temp variable
   temp = *num1;
 
   //Copy the value of num2 to num1
   *num1 = *num2;
 
   //Copy the value of num1 stored in temp to num2
   *num2 = temp;
}
 
int main() {
   int num1, num2;
 
   //Inputting 2 numbers from user
   cout<<"Enter the first number : ";
   cin>>num1;
   cout<<"Enter the Second number : ";
   cin>>num2;
 
   //Passing the addresses of num1 and num2
   swap(&num1, &num2);
 
   //Printing the swapped values of num1 and num2
   cout<<"First number : "<< num1;
   cout<<"Second number: "<<num2;
 
   return (0);
}


Enter the first number : 23
Enter the Second number : 5
First number : 5
Second number: 23

Conclusion

Here, we have learned how to implement a C++ program For Swapping Two Number In Function Using Pointer.



About the author:
Nikita Pandey is a talented author and expert in programming languages such as C, C++, and Java. Her writing is informative, engaging, and offers practical insights and tips for programmers at all levels.