Write a C++ program using the concept of OOP to calculate the factorial of a number.
Algorithm:
- Create a Factorial class with private variable number to store the number whose factorial is to be calculated.
 - Define a public method calculate() in the class to find the factorial of the stored number by using a for loop.
 - In the main() function, prompt the user to enter a number.
 - Create a Factorial object with the number entered by the user.
 - Call the calculate() method of the Factorial object to find the factorial of the number.
 - Print the factorial of the number.
 - 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