Find largest of three numbers using friend function

Find largest of three numbers using friend function is a simple program to find maximum among two number.

In this tutorial we will see what is friend function, how to find maximum number and program to find grater value among three number in c++.

Friend function definition : Friend function is a special function which is not in the scope of a class and it is used to access the private data member of the class.

As it is not in the scope of the class it can be defined in the public or private region of the class without affecting it’s meaning.

Friend function syntax

To declare the friend function the keyword friend is used.

friend return_type function_name(arguments);

Algorithm :

  1. Start
  2. Write class and declare friend function in class.
  3. Ed with the class
  4. Define friend function
  5. Write main function
  6. Create object
  7. Call function
  8. End

C++ program to find largest of three numbers using friend function

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677#include <iostream>using namespace std;class biggest  {    private:          int a,b,c,large;   public:          void getdata();friend int big(biggest abc);   }; void biggest::getdata()  {     cout<<“Enter any three number”<<endl;     cin>>a>>b>>c;   } int big(biggest abc)  {       abc.large=abc.a;       if(abc.b>abc.large)       {           abc.large=abc.b;        }       if(abc.c>abc.large)       {          abc.large=abc.c;        }     cout<<endl;     cout<<“largest number is = “<<abc.large;     return 0;  }int main()  {     biggest obj;     obj.getdata();     big(obj);    return 0;  }

Output :

c++ program to find largest of three numbers using friend function
c++ program to find largest of three numbers using friend function

Explanation :

1. Execution starts with the main function.

2. First we create a object of class

biggest obj;

3. Using object we call function 

obj.getdata();  => get call to function

void biggest::getdata() {  => function executed

cout<<“Enter any three number”<<endl;

cin>>a>>b>>c;  => a = 12 , b= 24 , c= 3

}  => returns to main function

4. Next we call friend function

big(obj);  => by passing class object

int big(biggest abc) {   => function executed

abc.large=abc.a;   => abc.large = 12

if(abc.b>abc.large) => 24 > 12 condition true

abc.large=abc.b;  => abc.large = 24

if(abc.c>abc.large)  3 > 24 => condition false block not executed

5. Now print largest value

cout<<endl; cout<<“largest number is = “<<abc.large;

=> largetst number is = 24

}  => return to main

6. End with the program