C Program – Loops Example – Find Factorial of a Number

In mathematics, the factorial of a positive integer number n is denoted by n!, and it is the product of all positive integers from 1 to less than or equal to n. Note that factorial of number 0 is 1 & factorial of a negative number doesn’t exist.

For example, factorial of number 5 is product of numbers from 1 to 5 as 1*2*3*4*5 which is 120.

The factorial of a positive number n is given by:

factorial of n (n!) = 1*2*3*4....n


C Program – Loops Example – To Find Factorial of Number

#include <stdio.h>
int main()
    int n, i;
    long fact = 1;


    printf("\n\tEnter Number : ");

    // if the user enters a negative integer , show message
    if (n < 0)
        printf("\n\t Factorial of a negative number doesn't exist.");
        for(i=1; i<=n; i++)
            fact = fact * i; 

        printf("\n\tFactorial of %d = %ld", n, fact);
    return 0;

In this program, variable n is to input number if it is less than zero , means it is negative hence show message as “factorial of negative number does not exists”.

if number n is positive , then find factorial by finding the product of numbers from 1 to n. here for loop is used for iteration. initially value of fact variable is 1.


1st iteration i=1  & value of fact is 1 , so new value of fact variable is fact=1*1  ,   which is 1

2nd iteration i=2  & value of fact is 1 , so new value of fact variable is fact=1*2  ,  which is 2

3rd iteration i=3  & value of fact is 2 , so new value of fact variable is fact=2*3  ,   which is 6

4th iteration i=4  & value of fact is 6 , so new value of fact variable is fact=6*4  ,   which is 24

5th iteration i=5  & value of fact is 24 , so new value of fact variable is fact=24*5 , which is 120

Download code : c-program-factorial-program-step-by-step-explain.c (108 downloads)

Output of program 



C Program – Loops Example – Fibonacci Series up to N terms