C++ program to swap two numbers using friend function

Last updated:4th Sep 2022

In this program, you will take two numbers as input from the user and swap the two numbers by using a friend function in c++.

 input:
a = 5, b = 20
output:
a = 20, b = 5

input:
a=10, b=15
output:
a=15, b=10 

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


#include<iostream>
using namespace std;

class StudyFame {
  private:
    int a, b;
  public:
    // get the data from the user
    void getData() {
      cout << "Enter Two Numbers: ";
      cin >> a >> b;
    }
  // print the number on the screen
  void display() {
    cout << "a = " << a << " b = " << b << endl;
  }
   // friend function
  friend void swap_number(StudyFame & s);
};

// swap the number
void swap_number(StudyFame & s) {
  int temp;
  /* accessing private members from the friend function */
  temp = s.a;
  s.a = s.b;
  s.b = temp;
}

int main() {

  // creating object of class
  StudyFame s;

  s.getData();
  cout << "Before swapping" << endl;
  s.display();

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

Related programs