English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Comprehensive Collection of C Programming Examples
In this example, you will learn to calculate the factorial of the number entered by the user.
To understand this example, you should understand the followingC programmingTopic:
The factorial of positive number n is:
factorial of n (n!) = 1 * 2 * 3 * 4....n
Factorial of negative numbers does not exist. The factorial of 0 is1.
#include <stdio.h> int main() { int n, i; unsigned long long fact = 1; printf("Enter an integer: "); scanf("%d", &n); //If the user enters a negative integer, display an error if (n < 0) printf("Error! Factorial of negative numbers does not exist."); else { for (i = 1; i <= n; ++i) { fact *= i; } printf("%d's factorial = %llu", n, fact); } return 0; }
Output result
Enter an integer: 10 10 factorial == 3628800
The program takes a positive integer from the user and calculates the factorial using a for loop.
Since the factorial of a number may be very large, the type declaration of the factorial variable is unsigned long long.
If the user enters a negative number, the program will display a custom error message.
You can alsoUse recursionFind the factorial of a number.