C++ Program to convert a decimal number into binary with friend function
Write a program in C++ to convert a decimal number into binary without using an array with a friend function.
If we declare a function friend int show(T4Tutorials_Decimal_Number);
as a friend in a class T4Tutorials_Decimal_Number
then this function friend int show(T4Tutorials_Decimal_Number);
can access the private and protected members of the class T4Tutorials_Decimal_Number
. 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 | #include <iostream> using namespace std; class T4Tutorials_Decimal_Number { protected: int i=1,j=n,n, binaryn=0; public: T4Tutorials_Decimal_Number() { cout<<" enter Decimal Number :"; cin>>n; for(j=n;j>0;j=j/2) { binaryn=binaryn+(n%2)*i ; i=i*10; n=n/2; } } friend int show(T4Tutorials_Decimal_Number); }; int show(T4Tutorials_Decimal_Number A) { cout<<"binary number ="<<A.binaryn<<endl; } int main() { T4Tutorials_Decimal_Number A; show(A); } |
Output
enter Decimal Number: 9
1001