Factorial program in C++ using class

 #include <iostream>


using namespace std;


class Factorial {

    private:

        int num;


    public:

        Factorial(int n) {

            num = n;

        }


        int calculate() {

            int fact = 1;

            for (int i = 1; i <= num; i++) {

                fact *= i;

            }

            return fact;

        }

};


int main() {

    int n;

    cout << "Enter a number: ";

    cin >> n;


    Factorial f(n);

    int result = f.calculate();


    cout << "The factorial of " << n << " is " << result << endl;


    return 0;

}



In this program, we define a class Factorial with a private member variable num and a public method calculate that returns the factorial of num. The constructor takes an integer argument n and sets num to n.

In the calculate method, we initialize a variable fact to 1 and loop from 1 to num, multiplying fact by the current loop variable at each iteration. This gives us the factorial of num.

In the main function, we prompt the user to enter a number and read it in using cin. We create an instance of the Factorial class with the user's input as the argument to the constructor. We call the calculate method on the Factorial instance and store the result in a variable result.

Finally, we print out the result using cout. The program returns 0 to indicate successful execution.

Post a Comment

0 Comments