C++ Program to find factorial using friend function


In this program, You will learn how to find factorial using friend function in C++.


friend void factorial(Test t);


Example: How to find factorial using friend function in C++

Run it Now
#include<iostream>
using namespace std;

class Test {
private:
    int n;
public:
    void input() {
        cout << "Enter a Number :";
        cin >> n;
    }

    friend void factorial(Test t);
};

void factorial(Test t) {

    int f = 1, i;
    for (i = 1; i <= t.n; i++) {
        f = f*i;
    }
    cout << "\nThe factorial is :" << f;
}

int main() {

    Test t;
    t.input();
    factorial(t);

    return 0;
}

Output:

Enter a Number :3
The factorial is :6