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++.

#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 << "Factorial is:" << f;
}

int main() {

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

    return 0;
}

Output:

Enter a number:4
Factorial is:24