Pages

C Program to Find Factorial of a Number


This is a simple C language program to find factorial of any number. In case you don't know what factorial is, factorial is the product of an integer and all the integers below it. For example:
5! = 1 * 2 * 3 * 4 * 5 = 120
The program first prompts for any integer. Then, finds the factorial using For Loop and prints the result.


Code


#include <stdio.h>
int main()
{int n, i, fac=1;
    printf("Enter any number: ");
    scanf("%d",&n);   
    for(i=1;i<=n;i++)
    fac = fac * i;    
    printf("Factorial: %d", fac);
    return 0;
}

Output


Program Output for C Factorial Program

#include <stdio.h>

This is a preprocessor directive.
Program execution starts with main()

int main()

We initialize three integer variables, namely 'n', 'i' and 'fac', and give an initial value of 1 to fac. The variable n holds the number that is input by the user. The variable 'i' acts as the loop counter.

    for(i=1;i<=n;i++)
    fac = fac * i;

Thus, the for loop initializes 'i' to 1, then checks if 'i' is less than or equal to 'n'. If condition is true, then the statement gets executed and 'i' is incremented by 1. Thus, the loop carries out the statement 'n' number of times.


Don't Forget to Share...