Table of Contents
Introduction
In this program, you will learn to calculate the factorial of a number.
A particular value will be entered by the user, and then through this program, we will compute its factorial.
For example, Factorial of 5 is (! is the symbol for factorial):
5! =5*4*3*2*1=120
Similarly, Factorial of 7 is
7! =7*6*5*4*3*2*1=5040
Factorial of negative numbers doesn’t exist.
Factorial of 0 and 1 is 1.
What is the use of this program?
It is easy to calculate the factorial up to certain values, but it is difficult to calculate factorial like 100! , 500! etc. A small code written in C will make this task quite easy.
To understand this example, you should know about the following C programming topics:
1. C data types
2. Operators in C
3. if-else statement
4. for loop
Program
#include<stdio.h> int main() { int x; printf("Enter an integer:\n"); scanf("%d",&x); int fact=1; if(x>0) // x is a positive integer { for (int i=1; i<=x; i++) { fact=fact*i; // fact is updated when value of i is multiplied in it } printf("Factorial of %d is %d",x,fact); } else if(x==0) // x is 0 { printf("Factorial of %d is 1",x); } else // x is a negative integer { printf("Factorial does not exist"); } return 0; }
Output
Explanation
In the above program, we have to calculate the factorial of ‘x’.
Now we have three conditions, either ‘x’ is a positive integer or ‘x’ is 0 or ‘x’ is a negative integer. if-else statements are used to check all these conditions.
If the value of ‘x’ is greater than 0 then the ‘if’ block will be executed.
for (int i=1; i<=x; i++)
‘i’ will start from 1 and iterate until it reaches ‘x’.
‘fact’ variable is initialized with 1. When the value of ‘i’ is 1, the statement
fact=fact*i; will return 1*1=1
Thus, fact=1
‘i’ is incremented and now its value is 2
fact=fact*i; will return 1*2=2
Thus, fact=2
i’ is incremented and now its value is 3
fact=fact*i; will return 2*3=6
Thus, fact=6
In the end when the value of ‘i’ reaches 10 then
fact=fact*i; will return 362880*10=3628800
thus fact=3628800
now ‘i’ is updated to 11 which will terminate the loop.
0 Comments