C++ program to swap two numbers using class

Last updated:4th Sep 2022

In this program, we will take two numbers from the user and perform a swapping of two number programs by using class.

input:
a = 10 b = 30
output:
a = 30 b = 10 

For example, if a user enters a=10 and b=30 then the output will be a=30 and b=10.


#include<iostream>

using namespace std;

class StudyFame {
  private:
    int a, b;
  public:
    void getData();
    void swap_number();
    void display();
};
// get the data from user
void StudyFame::getData() {
  cout << "Enter Two Numbers: ";
  cin >> a >> b;
}

// swap the number
void StudyFame::swap_number() {
  int temp;
  temp = a;
  a = b;
  b = temp;
}
// print the number on screen
void StudyFame::display() {
  cout << "a = " << a << " b = " << b << endl;
}
int main() {
    
 // creating object of class
  StudyFame s;
  
  s.getData();
  cout << "Before swapping" << endl;
  s.display();

  s.swap_number();
  cout << "After swapping" << endl;
  s.display();
  return 0;
}
output
Enter Two Numbers: 15   10
Before swapping
a = 15 b = 10
After swapping
a = 10 b = 15

In the above program, we have created one class named it StudyFame, inside the class, we have two variables and three methods.

  • getData(): this method we have used for taking two input numbers from the user.
  • swap_number(): this method performs swapping by using a temporary variable.
  • display(): it will display a message on the screen.

Related programs