Sum of n number of odd natural numbers by using friend class in C++.
If we declare a class friend class T4Tutorials_odd_number
as a friend in a class class T4Tutorials_friend_sum
then this class friend class T4Tutorials_odd_number
can access the private and protected members of the class class T4Tutorials_friend_sum
.
Syntax of friend function in C++
class class_name_T4Tutorials
{
…friend class name of the friend class;
…
}
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 |
#include<iostream> using namespace std; class T4Tutorials_friend_sum { private: int s=0; public: friend class T4Tutorials_odd_number; }; class T4Tutorials_odd_number { public: void disp(T4Tutorials_friend_sum u) { int n; cout<<"Please enter the value to print the odd Number."<<endl; cin>>n; cout<<"The output is."<<endl; for(int i=1;i<=n;i++) { cout<<2*i-1<<" "; u.s=u.s+(2*i-1); cout<<endl; } cout<<"The sum of the given input is: "<<u.s; } }; int main() { T4Tutorials_odd_number m; T4Tutorials_friend_sum u; m.disp(u); return 0; } |
Output
Please enter the value to print the odd Number.
5
The output is.
1
3
5
7
9
The sum of the given input is: 25