C Language

June 10, 2023

How to use factorial of a number in C language

Program to use factorial of a number in C language


#include <stdio.h>
long int factorial(int n);
int main()
{
    int num;
    printf("enter a number :");
    scanf("%d", &num);
    if (num < 0)
    {
        printf("no factorial of negative number\n");
    }

    else
    {
        printf("factorial of %d is %ld\n", num, factorial(num));
    }

    return 0;
}
long int factorial(int n)
{
    int i;
    long int fact = 1;
    if (n == 0)
        return 1;
    for (i = n; i > 1; i--)
    {

        fact *= i;
        printf("i %d\t fact %ld\n", i, fact);
    }
    return fact;
}

Output


i 5 fact 5
i 4 fact 20
i 3 fact 60
i 2 fact 120
factorial of 5 is 120

Tags:

by : Nadeem Khan

Quick Summary:

Program to use factorial of a number in C language copy #include <stdio.h> long int factorial(int n); int main() { int num; printf(“enter a number :”); scanf(“%d”, &num); if (num < 0) { printf(“no factorial of negative number\n”); } else { printf(“factorial of %d is %ld\n”, num, factorial(num)); } return 0; } long int factorial(int […]