C Program to find the Factorial of a given Number

In this section we will see how to write C Program to find the Factorial of a given Number.

Factorial is a function which multiplies the number to every number below it till it reaches to 1. The factorial is denoted by a (!) symbol.

For Eg. the factorial of 5 is 5! = 5 * 4 * 3 * 2 * 1 = 120

the factorial of 5 is 6! = 6 * 5 * 4 * 3 * 2 * 1 = 720

(NOTE:- The factorial of 0 is 1. 0! = 1)

Now let’s see the C Program to find the factorial of a given number using different methods.

Method 1 :- C Program using iteration process


#include<stdio.h>
int main(){
int n,fact=1;
printf("Enter the Number: ");
scanf("%d",&n);
for(int i=n;i>=1;i--){
fact = fact * i;
}
printf("%d",fact);
return 0;
}

Output:-

C Program to find the Factorial of a given Number

Method 2 :- C Program to using recursion

Here we see the recursion implementation of this program. The function kept calling itself until it meet the base condition given in the code.


#include<stdio.h>
int fact(int);
int main()
{
int n;
printf("Enter the number of which you want to find the factorial: ");
scanf("%d",&n);
printf("%d", fact(n)); 
return 0;
}

int fact(int n){
if(n==1)
return 1;
return (n*fact(n-1));
}

Output:-

C Program to find the Factorial of a given Number

Conclusion

In this article we have successfully seen how to write a C program to find the factorial of a given number using iteration process and recursion. I hope you understand the programs and cleared you doubt. If you have any questions feel free to ask in the comment section.

Related Articles

Leave a Reply