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

situs togel

situs togel

slot gacor hari ini

toto slot

situs toto

situs gacor

situs gacor

slot gacor

situs gacor

situs gacor

situs toto

situs toto

kampungbet

kampungbet

situs togel

situs togel

kampungbet

kampungbet

slot online

slot online

slot online

kampungbet

kampungbet

kampungbet

slot gacor

kampungbet

situs togel

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

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