# Write a c++ program to find out the sum of an A.P. series by using the friend function.

Write a c++ program to find out the sum of an A.P. series by using the friend function.

If we declare a function `friend int show(T4Tutorials_AP_Series);`

as a friend in a class `T4Tutorials_AP_Series`

then this function `int show(T4Tutorials_AP_Series);`

can access the private and protected members of the class `T4Tutorials_AP_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

{

…

friend return_type function_name(arguments);

…

}

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 32 33 34 35 36 37 38 39 |
#include<iostream> using namespace std; class T4Tutorials_AP_Series { protected : int n1, T4Tutorials_Difference, n2, i, ln, s1; public : input() { s1 = 0; cout << "Input the starting number of the A.P. series: "<<endl; cin >> n1; cout << "Input the number of items for the A.P. series: "<<endl; cin >> n2; cout << "Input the common difference of A.P. series: "<<endl; cin >> T4Tutorials_Difference; s1 = (n2 * (2 * n1 + (n2 - 1) * T4Tutorials_Difference)) / 2; ln = n1 + (n2 - 1) * T4Tutorials_Difference; } friend int show(T4Tutorials_AP_Series); }; int show (T4Tutorials_AP_Series a) { cout << "The Sum of the A.P. series are : "; for (a.i = a.n1; a.i <= a.ln; a.i = a.i + a.T4Tutorials_Difference) { if (a.i != a.ln) cout << a.i << " + "; else cout << a.i << " = " << a.s1 << endl; } } int main() { T4Tutorials_AP_Series a; a.input(); show(a); } |