Projects Inventory

C++ OOP program to find factorial with do while loop

C++ OOP program to find factorial with do while loop.

Certainly! Here’s an example C++ program that uses object-oriented programming (OOP) and a do-while loop to calculate the factorial of a given number:

Advertisement
#include <iostream>

class FactorialCalculator {
private:
    int number;

public:
    void setNumber(int n) {
        number = n;
    }

    int calculateFactorial() {
        int factorial = 1;
        int i = 1;

        do {
            factorial *= i;
            i++;
        } while (i <= number);

        return factorial;
    }
};

int main() {
    int num;
    std::cout << "Enter a number: ";
    std::cin >> num;

    FactorialCalculator calculator;
    calculator.setNumber(num);
    int result = calculator.calculateFactorial();

    std::cout << "Factorial of " << num << " is " << result << std::endl;

    return 0;
}
  • We define a class called FactorialCalculator that encapsulates the logic for calculating the factorial.
  • Advertisement
  • The setNumber function allows us to set the value for which we want to calculate the factorial, and the calculateFactorial function performs the actual calculation using a do-while loop.
  • In the main function, we prompt the user to enter a number, create an instance of the FactorialCalculator class, set the number using the setNumber function, and then calculate the factorial using the calculateFactorial function. Finally, we display the result on the console.
Exit mobile version