Find the Factorial of a number


Summary: Factorial is represented using '!', so five factorial will be written as (5!),n factorial as (n!).
n! = n*(n-1)*(n-2)*(n-3)...3.2.1 and zero factorial is defined as one i.e. 0! = 1.



Using While Loop
#include<stdio.h>
void main()
{
int a,f,i;
printf("Enter a number: ");
scanf("%d",&a);
f=1;
i=1;
while(i<=a)
{
f = f * i;
i++;
}
printf("\nFactorial of %d is: %d",a,f);
}


Using For Loop
#include<stdio.h>
void main()
{
int a,f,i;
printf("Enter a number: ");
scanf("%d",&a);
f=1;
for(i=1;i<=a;i++)
f = f * i;
printf("\nFactorial of %d is: %d",a,f);
}


Using Recursion
#include<stdio.h>
int fact(int);
int main(){
int num,f;

printf("\nEnter a number: ");
scanf("%d",&num);

f=fact(num);

printf("\nFactorial of %d is: %d",num,f);
return 0;
}

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



   

0 Comments