C program to find factorial of a number

Write a C program to input a number and calculate its factorial using for loop. How to find factorial of a number in C program using loop. Logic to find factorial of a number in C programming.

Example

Input

Input number: 5

Output

Factorial: 120

Required knowledge

Basic C programming, For loop

What is factorial?

Factorial of a number n is product of all positive integers less than or equal to n. It is denoted as n!.

For example factorial of 5 = 1 * 2 * 3 * 4 * 5 = 120

Logic to find factorial of a number

Step by step descriptive logic to find factorial of a number.

  1. Input a number from user. Store it in some variable say num.
  2. Initialize another variable that will store factorial say fact = 1.

    Why initialize fact with 1 not with 0? This is because you need to perform multiplication operation not summation. Multiplying 1 by any number results same, same as summation of 0 and any other number results same.

  3. Run a loop from 1 to num, increment 1 in each iteration. The loop structure should look like for(i=1; i<=num; i++).
  4. Multiply the current loop counter value i.e. i with fact. Which is fact = fact * i.

Program to find factorial of a number

/**
 * C program to calculate factorial of a number
 */

#include <stdio.h>

int main()
{
    int i, num;
    unsigned long long fact=1LL;

    /* Input number from user */
    printf("Enter any number to calculate factorial: ");
    scanf("%d", &num);

    /* Run loop from 1 to num */
    for(i=1; i<=num; i++)
    {
        fact = fact * i;
    }

    printf("Factorial of %d = %llu", num, fact);

    return 0;
}

Since factorial cannot be negative and can grow rapidly, therefore I have used unsigned long long data type to store factorial. If your compiler doesn’t supports long long then, you can use unsigned long which is guaranteed to run on all compilers. If you are using unsigned long then you also need to replace the format specifier from %llu to %lu.

Advance your skills by learning this program using recursive approach.

Read more – Program to find factorial using recursion.

Output

Enter any number to calculate factorial: 5
Factorial of 5 = 120

Happy coding 😉