Factorial is symbolized by an exclamation mark (!). Factorial of n number is the product of all integers greater than or equal to 1 but less than or equal to n.

To find the factorial, the number should be greater than or equal to 1. Factorial of 0 is defined as 1 and factorial of a negative number is impossible.

Find factorial of a number in C

Here is the code for finding the factorial of a number in C using recursion

#include <stdio.h>
int main()
{
    int number;

    printf("Enter a number to find factorial: ");
    scanf("%d", &number);

    int value;

    if (number < 0)
    {
        printf("Factorial of negative number is undefined please try again\n");
    }
    else
    {
        value = fact(number);
        printf("The Factorial of %d is %d.\n", number, value);
    }
    return 0;
}
int fact(int number)
{
    if (number == 0 || number == 1)
    {
        return 1;
    }
    else
    {
        return(number * fact(number - 1));
    }
}

Output

Factorial of a Number in C

Program Explanation

In the above C program, a variable number is declared to take input from the user. Moreover, the variable value is taken in which the calculated value of factorial will be stored. Then we applied checks using if statements.

If the number is negative then it is impossible to find factorial. To calculate the factorial, the number must be greater than or equal to 1. In else statement, we call a function fact(number) by passing the number variable as an argument.

Function fact(number) will return the calculated factorial value, and it is stored in the value variable.

In fact() function, we use if else statement. If condition checks the number variable value is equal to 1 or 0 by using the logical OR operator. If the condition is true then this is the section that will be executed and fact() function returns 1.

If the condition is false then the else section will be executed. In else section, the value of the number variable is multiplied by fact() value and return value. Then the compiler will move back to the main and print the calculated value on the screen.

Related Articles

Last modified: April 27, 2019