Factorial in C
The Factorial is the product of all positive descending integers of n. Factorial of n is denoted by n!.
For example:
4! = 4 X 3 x 2 X 1 = 24
5! = 5 X 4 X 3 x 2 X 1 = 120
Example Program for factorial by using "for
loop"
#include<conio.h>
#include<stdio.h>
void main()
{
clrscr();
int n, i;
long int f=1;
printf("Enter a number\n");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
f=f*i;
}
printf("Factorial of %d = %ld",n,f);
getch();
}
Example Program for factorial by using "Function"
#include<conio.h>
#include<stdio.h>
long int fac(int);
void main()
{
clrscr();
int n;
long int f;
printf("Enter a number\n");
scanf("%d",&n);
f=fac(n);
printf("Factorial of %d = %ld",n,f);
getch();
}
long int fac(int x)
{
long int f=1;
int i;
if(x==1)
return(1);
else
for(i=1;i<=x;i++)
{
f=f*i;
}
return(f);
}
Example Program for factorial by using "Recursion"
//C Program to find factorial
//of an inputted number by function
#include<conio.h>
#include<stdio.h>
long int fac(int);
void main()
{
clrscr();
int n;
long int f;
printf("Enter a number\n");
scanf("%d",&n);
f=fac(n);
printf("Factorial of %d = %ld",n,f);
getch();
}
long int fac(int x)
{
if(x==1)
return(1);
else
return x * fac(x-1);
}
youtube video
No comments:
Post a Comment