C Program to find Factorial of a number


May 2, 2022, Learn eTutorial
959

For a better understanding, we always recommend you to learn the basic topics of C programming listed below:

In this C program, we have to find out the Factorial of a given number. So first, we have to check what is Factorial.

What is the factorial of a number?

The factorial of a number means the product of all the natural numbers up to the given number. An exclamation mark indicates the factorial of a number '!'. Let us consider an example: the factorial of 5 is 5! = 5 * 4 * 3 * 2 * 1. Which is equal to 120.

The logic we applied in this c program is to declare the variable 'i,' num, fac. Then read the number from the user and save it into the variable num. By using a for loop with the condition "i <= n" , calculate fact = fact * i. Finally, display the factorial of the number as 'fact'. the syntax of the if-else statement is

What is the syntax of the if-else statement?


if (testExpression) {

  // codes inside the body of if

} else {

  // codes inside the body of else

}

If the test expression is True, then we execute the code inside the if condition, and else parts are skipped. But if the test expression is False, we run the else part and ignore the if condition.

ALGORITHM

STEP 1: Include the header files to use the built-in function in the C program.

STEP 2: Declare the integer variable i, fact, num, and set fact=1.

STEP 3: Read the number from the user and save it into the variable num.

STEP 4: Check if the number is less than or equal to zero if valid, then set 'fact=1' and do step 6. Else do step 5.

STEP 5: By using the for loop with the condition i<=num, calculate fact=fact*i.

STEP 6: Display Factorial of the number num as fact.

C Source Code

                                          #include <stdio.h>

void main() {
  int i, fact = 1, num;
  printf("Enter the number\n");
  scanf("%d", & num);
  if (num <= 0)
    fact = 1;
  else {
    for (i = 1; i <= num; i++) /* multiplying each number below the given number to get the factorial */ {
      fact = fact * i;
    }
  } /* End of else */
  printf("Factorial of %d =%d\n", num, fact);
} /* End of main() */
                                      

OUTPUT

Enter the number
5

Factorial of 5 =  120