Objective:
Write a C++ program to calculate the factorial of a number using a while loop.
Task:
- Write a program that prompts the user to enter a number.
- The program should calculate the factorial of that number using a
whileloop and display the result.
Code:
#include <iostream>
using namespace std;
int main() {
int num, factorial = 1;
cout << "Enter a number: ";
cin >> num;
if (num < 0) {
cout << "Factorial is not defined for negative numbers." << endl;
} else {
int i = 1;
while (i <= num) {
factorial *= i;
i++;
}
cout << "The factorial of " << num << " is: " << factorial << endl;
}
return 0;
}Explanation:
This program prompts the user to enter a number (num).
It checks if the number is negative. If negative, it outputs that the factorial is not defined for negative numbers.
It uses a while loop to calculate the factorial of the number by multiplying the factorial variable with numbers from 1 to num.
The result is displayed using the cout statement.
Expected Output:
Enter a number: 5
The factorial of 5 is: 120