Write a C++ program to find Strong Numbers within a range of numbers by using friend function in C++.
If we declare a function int disp(T4Tutorials_Strong_Numbers);
as a friend function friend int disp(T4Tutorials_Strong_Numbers);
in a class class T4Tutorials_Strong_Numbers
, then this function int disp(T4Tutorials_Strong_Numbers);
can access the private and protected members of the class T4Tutorials_Strong_Numbers
. 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_Strong_Numbers
{…
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 49 50 51 |
#include<iostream> using namespace std; class T4Tutorials_Strong_Numbers { protected : int i, n, n1; int s1 , j, k; int en, sn; long T4Tutorials_factorial; public : input() { s1 = 0; T4Tutorials_factorial = 0; cout<<"Please input the starting range of number : "<<endl; cin>>sn; cout<<"Please input the ending range of number : "<<endl; cin>>en; } friend int disp(T4Tutorials_Strong_Numbers); }; int disp(T4Tutorials_Strong_Numbers a) { cout<<"The Strong numbers are: "<<endl; for (a.k = a.sn; a.k <= a.en; a.k++) { a.n1=a.k; a.s1 = 0; for (a.j = a.k; a.j > 0; a.j = a.j / 10) { a.T4Tutorials_factorial = 1; for (a.i = 1; a.i <= a.j % 10; a.i++) { a.T4Tutorials_factorial = a.T4Tutorials_factorial * a.i; } a.s1 = a.s1 + a.T4Tutorials_factorial; } if (a.s1 == a.n1) { cout << a.n1 << " "; } } cout<<endl; } int main() { T4Tutorials_Strong_Numbers a; a.input(); disp(a); } |
Output
Please input the starting range of number :
1
Please input the ending range of number :
10
The Strong numbers are:
1 2