Write a C program to find Factorial of a user input number, using for loop.
Related Read:
For Loop In C Programming Language
C Program To Find Factorial of a Number using While Loop
Example:
Factorial of 5 is 120 (1 x 2 x 3 x 4 x 5 = 120).
In general, n objects can be arranged in n(n – 1)(n – 2) … (3)(2)(1) ways. This product is represented by the symbol n!, which is called n factorial. By convention, 0! = 1.
#include<stdio.h> int main() { int num, count, fact = 1; printf("Enter a number to find its Factorial\n"); scanf("%d", &num); for(count = 1; count <= num; count++) { fact = fact * count; } printf("Factorial of %d is %d\n", num, fact); return 0; }
Output 1:
Enter a number to find its Factorial
5
Factorial of 5 is 120
Output 2:
Enter a number to find its Factorial
4
Factorial of 4 is 24
Output 3:
Enter a number to find its Factorial
3
Factorial of 3 is 6
Output 4:
Enter a number to find its Factorial
6
Factorial of 6 is 720
Output 5:
Enter a number to find its Factorial
0
Factorial of 0 is 1
C Program To Find Factorial of a Number using For Loop
If user enters num as 4. Then here are the values of variable count and fact for each iteration of for loop.
Iteration 1
count = 1;
fact = 1;
fact = fact * count;
fact = 1 * 1;
count = 2; // value of count increments by 1 for each iteration.
fact = 1;
Iteration 2
count = 2;
fact = 1;
fact = fact * count;
fact = 1 * 2;
count = 3; // value of count increments by 1 for each iteration.
fact = 2;
Iteration 3
count = 3;
fact = 2;
fact = fact * count;
fact = 2 * 3;
count = 4; // value of count increments by 1 for each iteration.
fact = 6;
Iteration 4
count = 4;
fact = 6;
fact = fact * count;
fact = 6 * 4;
count = 5; // value of count increments by 1 for each iteration.
fact = 24;
Now the value of count is 5, which is greater than the user input number 4. So the control exits for loop. We print the value present inside variable fact as the Factorial of the number. So in this case, 24 is the Factorial of number 4.
For list of all c programming interviews / viva question and answers visit: C Programming Interview / Viva Q&A List
For full C programming language free video tutorial list visit:C Programming: Beginner To Advance To Expert