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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
#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.
