C program to find factorial of any number

Previous Program Next Program

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

Example

Input

Input number: 5

Output

Factorial: 120

Required knowledge

Basic C programming, For loop

What is factorial?

Factorial of any number is the product of all positive integers less than or equal to n. It is denoted by n!. For example factorial of 5 = 1 * 2 * 3 * 4 * 5 = 120

Logic to find factorial

Initially beginners finds this as a tough exercise. But trust me, you will find this easy after I decode the logic. I have divided the logic for factorial in four simple and easy steps.

  1. Read a number from user. Store it in some variable say num.
  2. Initialize another variable that will store factorial say fact = 1. Now why initialized 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, incrementing 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

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

#include <stdio.h>

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

    /* Read a 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 = %lld", num, fact);

    return 0;
}

Factorial can grow very rapidly. Therefore, I have used long long data type for storing factorial. If your compiler doesn't supports long long data type. Then in case you can use long data type which is guaranteed to run on all platforms. If you are using long data type then you also need to replace the format specifier from %lld to %ld.

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

Happy coding ;)

Recommended posts

Previous Program Next Program

Labels: , , ,