The factorial of a number is the product of all the numbers from 1 to that number. For example,
factorial of 5 is equal to 1 * 2 * 3 * 4 * 5 = 120.
The factorial of a positive number n is given by:
factorial of n (n!) = 1 * 2 * 3 * 4.....n
The factorial of negative numbers do not exist and the factorial of 0 is 1.
Example: Find Factorial
Output
Enter a positive integer: 5 The factorial of 5 is 120.
In the above program, the user is prompted to enter an integer. Then if...else if...else statement is used to check the condition of a number.
- When the user enters a negative number, an error message is shown.
- When the user enters 0, the factorial is 1.
- When the user enters a positive integer, a
forloop is used to iterate over 1 to the number entered by the user to find the factorial. - Each number is multiplied and stored in the
factvariable.