In my previous posts, I have told you about the loops we use in c programming. You must have knowledge about the loops in order to make the factorial program in c. Today I am going to make this program using a while loop because we have to multiply numbers multiple times.
Factorial program in C using while loop
#include<stdio.h>
main()
{
int n, i=1;
printf("enter number");
scanf("%d", &n);
while(n>0)
{
i=i*n;
n--;
}
printf("%d",i);
}
If input = 4
then outpur = 24
If input = 5
then output = 120 ... etc
Also read: Loops In C Language For, While and Do While
This is a dynamic program where it takes input from the user and gives the factorial of that number as its output. But it is restricted up to some numbers because factorial of numbers greater than 16 can go in huge numbers.
Explanation
- In the braces of the main() function, I have started with int (integer data type) and declared two integer type variables n and i to store the input and 1.
int n, i=1;
- Now passed the message to enter the number and stores the inputted number in the variable n.
printf("enter number");
scanf("%d", &n);
- Declared the while loop and passed the condition that n must be greater than zero.
- Inside the loop, multiply the values of i and n and store it in the variable i and decrease the value of n by one unit (n–).
- These steps will repeat until n becomes zero.
while(n>0)
{
i=i*n;
n--;
}
- Now we have our output (factorial) in the variable i all we have to do it to print it.
printf("%d",i);

Also read: C Program for Right-Angle Triangle (Pythagoras Theorem)
Now you know the logic behind the factorial program. Try to make this program using for and do-while loops. Just apply the same logic and used their respective syntax to make this program. Soon I will teach you how to make the factorial program in c using recursion and function.