C++ Examples

C++ program to swap two numbers using class.

#include<iostream>
using namespace std;

class swapTwoNumbers
{
    public:
    int num1,num2;
    
    void getData();
    void SwapTwoValues();
    void display();
    
};

void swapTwoNumbers::getData()
{
    cout<<"Enter the first number ";
    cin>>num1;
    cout<<"Enter the second number ";
    cin>>num2;
}

void swapTwoNumbers::SwapTwoValues()
{
    swap(num1,num2);
}

void swapTwoNumbers::display()
{
    cout<<"The numbers are "<<num1<<" "<<num2<<endl;
}

int main()
{
    swapTwoNumbers obj;
    
    obj.getData();
    cout<<"Before swapping "<<endl;
    obj.display();
    
    obj.SwapTwoValues();
    
    cout<<"After swapping "<<endl;
    obj.display();
    
    return 0;
}

Output

Enter the first number 45
Enter the second number 86
Before swapping 
The numbers are 45 86
After swapping 
The numbers are 86 45
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments