C program to find factorial of any number

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. C program to find and display factorial of any given number.

Example:
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 numbers 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

Finding factorial is really easy you just need to know how to iterate over a loop. Finding factorial can be basically divided two steps:
  1. Run a loop from 1 to n (where n is the number whose factorial is to be found).
  2. Multiply the current loop counter value with fact (where fact is a variable that stores factorial and is initially initialized with 1).

Program to find factorial

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

#include <stdio.h>

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

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

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

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

    return 0;
}

Note: We know that factorial can grow very rapidly therefore, I have used long long data type for storing factorial. Also 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. Also if you are using long data type then you also need to replace the format specifier from %lld to %ld.

Note: Advance your skills by learning this program using recursive approach - C program to find factorial using recursion.

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

Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment