Index « Previous Next »

Question

Write a program that prompts the user to input a number and prints its factorial.

The factorial of an integer n is defined as
n! = 1 x 2 x 3 x ... x n; if n > 0
    = 1; if n = 0
For instance, 6! can be calculated as 1 x 2 x 3 x 4 x 5 x 6.

Source Code

#include <stdio.h>

int main()
{
    int i, n, fact = 1;
    
    printf("Enter a number :");
    scanf("%d", &n);

    for (i = 1; i <= n; i++)
    {
        fact *= i;
    }

    printf("The factorial of %d is %d.", n, fact);
    
    return 0;
}

Output

Enter a number :6
The factorial of 6 is 720.