C program to calculate factorial of given number.

Posted by Mangesh on March 14, 2018

/* Program to calculate factorial */

Description :

A factorial is a function that multiplies a number by every number below it till 1. For example 5!= 5*4*3*2*1=120. And factorial of zero is 1.

Logic :

We have use recursive approach to solution this problem. factorial of 1 = 1 (i.e. 1)
factorial of 2 = 2 (i.e. 1 * 2)
factorial of 3 = 6 (i.e. 2 * 3)
factorial of 4 = 24 (i.e. 6 * 4)
factorial of 5 = 25 (i.e. 24 * 5)
Factorial of any number is factorial of its previous number multiply by the number itself.

Program :

#include<stdio.h>
#include<conio.h>
int fact(int num)
{
   if(num ==0 || num==1)
      return 1;
   else
      return fact(num-1)*num;
}
void main()
{
   int number;
   printf("Enter the number: ");   
   scanf("%d",&number);
   printf("Factorial of %d is %d",number,fact(number));
   getch();
}


Output :

c program for factorial code tested in turbo c 3.2.

Skills Learned :

Arithmetic operation.
Basic recursive building.

Written with from Mangesh.

Related Post
1 C program to calculate factorial of given number.
2 C program to convert decimal number to binary number.
3 C program to find the G.C.D. of two number.
Latest Post
1 C program to implement Queue using linked list.
2 C program for binary search tree (BST).
3 C program to search an element in linked list.
4 C program for postorder traversal in binary tree.
5 C program for preorder traversal in binary tree.