Program:
#include <iostream>
using namespace std;
int main() {
int n, fact = 1;
cout << "Enter a positive integer: ";
cin >> n;
if(n < 0) {
cout << "Error: Please enter a positive integer" << endl;
return 1;
}
for(int i = 1; i <= n; ++i) {
fact *= i;
}
cout << "Factorial of " << n << " is " << fact << endl;
return 0;
}
Output:
Here is how this program works:
1. The code prompts the user to enter a positive integer and reads it from the standard input using the
cin
statement.2. An integer variable
fact
is initialized with a value of 1, which will store the entered number's factorial.3. The code checks whether the entered number is less than zero. If it is, an error message is printed to the console and the program terminates with a return code of 1. This is done to ensure that the entered number is positive, as the factorial is defined only for positive integers.
4. A
for
loop is used to compute the factorial of the entered number. The loop variable i
is initialized to 1 and iterates until i
is greater than the entered number n
.5. In each iteration of the loop, the current value of
fact
is multiplied by the value of i
, and the result is stored back in fact
. This updates the value of fact
to be the product of all the integers from 1 to n
.6. After the loop completes, the final value of
fact
contains the factorial of the entered number, which is printed to the console using the cout
statement.7. The program terminates with a return code of 0, indicating successful execution.