C Program to Find Factorial of a Number

What is Factorial?

Factorial is a multiplication operation of numbers with all the numbers that are less than it.

The formula to find the factorial of a number is

n! = n × (n-1) × (n-2) × (n-3) × ….× 3 × 2 × 1

For example:

Factorial 5 is:
5! = 120 (5*4*3*2*1 =120)

Here is an example of a C Program that calculates the factorial of a given number: The program takes input from the user and calculates the factorial using a for loop. The result is then displayed on the screen.

#include <stdio.h>

int main() {
  int num, factorial = 1;
  
  printf("Enter a number: ");
  scanf("%d", &num);
  
  for (int i = 1; i <= num; i++) {
    factorial = factorial * i;
  }
  
  printf("Factorial of %d = %d", num, factorial);
  
  return 0;
}

Output:

Enter a number: 5
Factorial of 5 = 120

The above C program calculates the factorial of a given number. The program starts with “stdio.h”, which provides functions for input/output operations in C.

In the “main” function, two variables are declared: “num” to store the input number, and “factorial” to store the result. The “printf” function is used to prompt the user to enter a number, and the “scanf” function is used to read the input into the “num” variable.

Also, a for “loop” is used to calculate the factorial. The loop starts from “i = 1” and goes up to “i = num”. In each iteration of the loop, the value of “factorial” is updated by multiplying it by “i”. The loop continues until all the values from “1” to “num” have been multiplied to get the final result.

Now, the result is displayed on the screen using the “printf” function.

Leave a Comment