Write a C++ program using the concept of OOP to calculate the factorial of a number


Write a C++ program using the concept of OOP to calculate the factorial of a number.

Algorithm:

  1. Create a Factorial class with private variable number to store the number whose factorial is to be calculated.
  2. Define a public method calculate() in the class to find the factorial of the stored number by using a for loop.
  3. In the main() function, prompt the user to enter a number.
  4. Create a Factorial object with the number entered by the user.
  5. Call the calculate() method of the Factorial object to find the factorial of the number.
  6. Print the factorial of the number.
  7. End the program.


Coding in C++:

#include <iostream>
using namespace std;
 
class Factorial {
  private:
    int number;
 
  public:
    Factorial(int num) {
      number = num;
    }
 
    int calculate() {
      int result = 1;
      for (int i = 1; i <= number; i++) {
        result *= i;
      }
      return result;
    }
};
 
int main() {
  int num;
 
  cout << "Enter a number: ";
  cin >> num;
 
  Factorial f(num);
 
  cout << "Factorial: " << f.calculate() << endl;
 
  return 0;
}
 

#OOP
#HappyProgramming
#HappyCoding

No comments:

Post a Comment