C Program to find factorial of a given number

      The factorial of a given number is computed by multiplying all the numbers starting from 1 through that given number. For example if we take 4 as given number then 4! is computed by calculating 1*2*3*4. This factorial program computes this value by using for loop which iterates from 1 through that given number,computing factorial of a given number.

factorial program in c



Source Code :

#include<stdio.h>
int main(){
  int i,f=1,num;
 
  printf("Enter a number: ");
  scanf("%d",&num);                 //Step 1
 
  for(i=1;i<=num;i++)               //Step 3
      f = f*i;                        //Step 2
 
  printf("Factorial of %d is: %d",num,f); //Step 4
  return 0;
}


edit-code-image

Sample Test cases:

1. Enter a number : 0
   Factorial of 0 is : 1
   
2. Enter a number : 1
   Factorial of 1 is : 1
   
3. Enter a number : 4
   Factorial of 4 is: 24

Explanation:

Step 1: Program reads a number from the user using scanf() function.

Step 2: The factorial of a given number is computed by multiplying 1 through that given number and is stored in the variable ‘f’.

Step 3: The for loop is iterated from 1 through that given number, incrementing by 1.

Step 4: Finally the factorial value stored in variable ‘f’ is printed to output screen using printf() function.

More about Factorial : Factorial
More content from topoint.in : Explore Content