Factorial calculation with C++ do-while loop

Estimated read time 1 min read

In this example, we show how to calculate factorial using the do while loop.

#include <iostream>
using namespace std;

int calculateFactorial(int number) {
    int result = 1;
    for (int i = 1; i <= number; i++) {
        result *= i;
    }
    return result;
}

int main() {
    int inputNumber;
    char exitKey;
    
    do {
        cout << "Enter a number between 1 and 10: ";
        cin >> inputNumber;
        
        if (inputNumber < 1) {
            cout << "Number must be greater than 0.\n";
        } else if (inputNumber > 10) {
            cout << "Number must be less than or equal to 10.\n";
        } else {
            int factorial = calculateFactorial(inputNumber);
            cout << "Result: " << factorial << endl;
        }
        
        cout << "Press 'h' to exit, any other key to continue: ";
        cin >> exitKey;
    } while (exitKey != 'h');
    
    return 0;
}
İbrahim Korucuoğlu

Yazar, bilişim ve teknoloji alanında derlediği faydalı içerikleri bu blogta paylaşmaktadır.