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:
#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
FactorialCalculatorthat encapsulates the logic for calculating the factorial. - The
setNumberfunction allows us to set the value for which we want to calculate the factorial, and thecalculateFactorialfunction performs the actual calculation using a do-while loop. - In the
mainfunction, we prompt the user to enter a number, create an instance of theFactorialCalculatorclass, set the number using thesetNumberfunction, and then calculate the factorial using thecalculateFactorialfunction. Finally, we display the result on the console.