Sum of the series Using friend function in C++.

If we declare a function `int show(T4Tutorials_SERIES n)`

as a friend in a class `T4Tutorials_SERIES;`

then this function `show()`

can access the private and protected members of the class `T4Tutorials_SERIES`

. You must know that a global function can also be declared as a friend function of the class.

**Syntax of friend function in C++**

class class_name_T4Tutorials

{

…

friend return_type function_name(arguments);

…

}

## C++ Program to show the Sum of the series Using friend function

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
#include <iostream> using namespace std; class T4Tutorials_SERIES { private: int n; int k=9; int sum=0; public: T4Tutorials_SERIES() { cout<<"Please enter a number: "; cin>>n; for(int i=1;i<=n;i++) { sum=sum+k; k=k*10+9; } } friend int show(T4Tutorials_SERIES); }; int show(T4Tutorials_SERIES n) { cout<<"Hi, the sum of T4Tutorials_SERIES is: "<<n.sum; } int main() { T4Tutorials_SERIES n; show(n); } |

**Output**

Please enter a number:

4

Hi, the sum of T4Tutorials_SERIES is:

11106

- List of Public service commissions - August 31, 2020
- Comparison of fee structure of Pakistani Universities - June 1, 2020
- Past Guess Paper of Auditing - May 12, 2020