Introduction
In this lab, we will learn how to write a C program to find the factorial of a number. We will use a simple algorithm to calculate the factorial using a loop.
Note: You need to create the file
~/project/main.cyourself to practice coding and learn how to compile and run it using gcc.
cd ~/project
## create main.c
touch main.c
## compile main.c
gcc main.c -o main
## run main
./main
Understanding Factorial
Factorial (denoted by n!) for a number (say n) is the product of all the numbers before n with the number itself. We can say that,
!n = n * !(n - 1)
For example,
!6 = 6 * 5 * 4 * 3 * 2 * 1 = 720
!12 = 12 * 11 * 10 * 9 * 8 * 7 * !6 = 479,001,600
Important points:
- Factorial of 0 is 1
- Factorial of negative numbers does not exist.
Writing the Algorithm
Here are the steps to be followed for the factorial program:
- Declare variables
nandfact=1.nis the number whose factorial is to be calculated andfactis the variable in which we will store the result. - Read input from the user in
n. - Initialize loop iterator
i=1and run the loop tilli<=n - Do the following in each iteration of the loop :
fact=fact*ii++
- Print
fact.
Writing the C Program
In this program, we will use a for loop to find the factorial of a number.
#include<stdio.h>
int main()
{
int n,i;
long int fact=1;
printf("Enter the number: ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
fact=fact*i; // calculating factorial
}
printf("Factorial of %d is %ld",n,fact);
return 0;
}
Testing the Program
Let's test our program by running it and checking the output.
Enter the number: 5
Factorial of 5 is 120
Final Program
Here is the final program that finds the factorial of a number using a for loop:
#include<stdio.h>
int main()
{
int n,i;
long int fact=1;
printf("Enter the number: ");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
fact=fact*i; // calculating factorial
}
printf("Factorial of %d is %ld",n,fact);
return 0;
}
Summary
In this lab, we learned how to write a C program to find the factorial of a number using a for loop. We used a simple algorithm and followed a step-by-step process to achieve our goal. The program takes an input from the user, calculates the factorial using a loop, and prints the result on the screen. We covered some important points like the initialization of variables and the limits of int and long int data types.



