Factorial Program In C
Factorial Program in C: Factorial of n is the product of all positive descending integers. Before going to see factorial program in c we will see what is the factorial means. lets see what is concept of factorial number-What is a Factorial Number
factorial number is nothing but the multiplication of all smaller numbers of that particular number including itself. for better understanding see the following example-
if we want to ascertain 5!(factorial of 5) then,
5!=5*4*3*2*1
means 5!=120.(factorial of 5 is 120)
(note: factorial is denoted by '!' mark.)
we can write factorial program using many ways ,but here we will see the programs using for loop,while loop and c factorial program using function recursion.
C factorial Program : Using For loop
#include<stdio.h>
void main()
{
int num,i;
int fact=1;
printf("Enter a number To Find Out Factorial: ");
scanf("%d",&num);
for(i=1;i<=num;i++){
fact=fact*i;
}
printf("The Factorial of %d is: %d",num,fact);
getch();
}
Output:
Enter a number To Find Out Factorial: 4
The Factorial of 5 is: 24
C Factorial Program: Using While Loop
#include<stdio.h>
# include<conio.h>
void main()
{
int num,fact=1,copyno=0;
printf("Enter Number To Findout Factorial:");
scanf("%d",&num);
copyno=num;
while(num>0)
{
fact=fact*num;
num--;
}
printf("Factorial of %d is:%d",copyno,fact);
getch();
}
Output:
Enter Number To Findout Factorial:3
Factorial of 3 is :6
C Factorial Program : Using Function Recursion
#include<stdio.h>
long fact(int n)
{
if (num == 0)
return 1;
else
return(num * factorial(num-1));
}
void main()
{
int num;
long factNum;
printf("Enter a number To Find Out Factorial: ");
scanf("%d", &num);
factNum = fact(num);
printf("Factorial of %d is %ld\n", num, factNum);
getch();
}
Output:
Enter a number To Find Out Factorial: 5
Factorial of 5 is: 120
Post a Comment