Problem statement
Write a program to take a number as an input from user and find the factorial of that number.
How to find factorial of a number
Factorial of a non-negetive number is denoted by n!.
Factorial of a number n is the product of all positive integers less than or equal to n.
For example:
1 2 |
5! = 5 * 4 * 3 * 2 * 1 = 120 |
Note: Factorial of a 0! = 1.
C program to find factorial of a given number
1 2 3 4 5 6 7 8 9 10 11 |
#include < stdio.h > int main() { int i, num, fact = 1; printf("Enter the no: \t"); scanf("%d", & num); for (i = 1; i <= num; i++) { fact = i * fact; } printf("factorial of a number %d is %d", num, fact); } |
Output
1 2 3 |
Enter the no: 5 factorial of a number 5 is 120 |
C Program to find factorial of a number using recursion
What is recursion?
The process in which a function calls itself directly or indirectly is called recursion.
And this function is called as a recursion function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
#include<stdio.h> int fact(int); int main() { int num, i=1, factorial; printf("Enter the number\n"); scanf("%d", &num); factorial = fact(num); printf("Factorial of a %d is %d", num, factorial); getchar(); getchar(); } int fact(int a) { if(a==0) { return 1; } else { return (a * fact(a-1)); } } |
Output
1 2 3 |
Enter the number 6 Factorial of a 6 is 720 |