C++ Examples

C++ program to swap two numbers using pointers.

#include<iostream>
using namespace std;

//function to swap two numbers

void swapValue(int *number1, int *number2)
{
    swap(*number1,*number2);
}

int main()
{   
    int x,y;
    
    cout<<"Enter the first number to swap ";
    cin>>x;
    cout<<"Enter the second number to swap ";
    cin>>y;
    
    cout<<"Before swapping the numbers are "<<x<<" and "<<y<<endl;
    
    swapValue(&x,&y);
    
    cout<<"After swapping the numbers are "<<x<<" and "<<y;
    
    return 0;
}

Output

Enter the first number to swap 45
Enter the second number to swap 78
Before swapping the numbers are 45 and 78
After swapping the numbers are 78 and 45

Another method - Using inbuilt swap function

#include<iostream>
using namespace std;

int main()
{   
    int x,y,*a,*b;
    
    cout<<"Enter the first number to swap ";
    cin>>x;
    cout<<"Enter the second number to swap ";
    cin>>y;
    
    cout<<"Before swapping the numbers are "<<x<<" and "<<y<<endl;
    
    a = &x;
    b = &y;
    
    //inbuilt swap function to swap two numbers
    
    swap(a,b);
    
    cout<<"After swapping the numbers are "<<*a<<" and "<<*b;
    
    return 0;
}
Enter the first number to swap 25  
Enter the second number to swap 67
Before swapping the numbers are 25 and 67
After swapping the numbers are 67 and 25
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments