Write a program in C++ to print Floyd’s Triangle by using the friend function.
If we declare a function friend int show(T4Tutorials_Floyds_Triangle);
as a friend in a class T4Tutorials_Floyds_Triangle
then this function int show (T4Tutorials_Floyds_Triangle a)
can access the private and protected members of the class T4Tutorials_Floyds_Triangle
.
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 40 41 42 43 44 45 46 47 48 |
#include<iostream> using namespace std; class T4Tutorials_Floyds_Triangle { public: int i,j,p,q,n; public: int Floyds_Pattern() { cout<<"enter no.of rows"; cin>>n; } friend int show(T4Tutorials_Floyds_Triangle); }; int show (T4Tutorials_Floyds_Triangle a) { for(a.i=1;a.i<=a.n;a.i++) { if(a.i%2==0) { a.p=1; a.q=0; } else { a.p=0; a.q=1; } for(a.j=1;a.j<=a.i;a.j++) { if(a.j%2==0) { cout<<a.p; } else { cout<<a.q; } } cout<<endl; } } int main() { T4Tutorials_Floyds_Triangle a; a.Floyds_Pattern(); show(a); } |
Output