Quantcast
Channel: C Programming Archives - QnA Plus
Viewing all articles
Browse latest Browse all 93

C Program to Calculate Factorial of a Number

$
0
0

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

The post C Program to Calculate Factorial of a Number appeared first on QnA Plus.


Viewing all articles
Browse latest Browse all 93

Trending Articles