C Program to Calculate Factorial of a Number

Factorial of a number N, (N!) is 1*2*3*4*5*…..*N. Here we’ll see how to write C program to calculate the factorial value of a number.

Here are the C functions that calculate the factorial value of a the input number.

Using FOR Loop

unsigned long factorial(int n) {
    unsigned long f = 1;
    int i;
    
    for(i = 1; i <= n; i++) {
        f *= i;
    }
    
    return f;
}

Using WHILE Loop

unsigned long factorial(int n) {
    unsigned long f = 1;
    
    while(n) f *= n--;
    
    return f;
}

Using Recursion

unsigned long factorial(int n) {
    if(n == 0) return 1;
    
    return factorial(n-1) * n;
}

Complete Program

Any one of the above functions can be used in the program.

#include <stdio.h>

unsigned long factorial(int n) {
    unsigned long f = 1;
    
    while(n) f *= n--;
    
    return f;
}

int main()
{
    int n;
    unsigned long f = 0;
    
    printf("Enter a number: ");
    scanf("%d", &n);
    
    if(n < 0) {
        printf("Factorial not possible for a negative number.\n");
        return 0;
    }
    
    f = factorial(n);
    printf("Factorial of %d is %lu", n, f);
    
    return 0;
}

Here is the output of the program.

factorial of a number

Author: Srikanta

I write here to help the readers learn and understand computer programing, algorithms, networking, OS concepts etc. in a simple way. I have 20 years of working experience in computer networking and industrial automation.


If you also want to contribute, click here.

Leave a Reply

Your email address will not be published. Required fields are marked *

0
0
0
0
0
0