C++ Program to find factorial of a number using constructor


In this program, You will learn how to find factorial of a number using a constructor in C++.


3! = 1 * 2 * 3

4! = 1 * 2 * 3 * 4


Example: How to find factorial of a number using constructor in C++

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

class Test {
    int n, i, f;
public:

    Test() {
        cout << "Enter a number : ";
        cin>>n;

        f = 1;
        for (i = 1; i <= n; i++) {
            f = f*i;
        }
    }

    void display() {
        cout << "\nFactorial is : " << f;
    }
};

int main() {

    Test obj1;
    obj1.display();

    return 0;
}

Output:

Enter a number : 4
Factorial is : 24