## C Program To Find Factorial of a Number

This c program is used to find the factorial value for any number.

## Factorial Algorithm:

Factorial of a Number = 1*2* .... (Number-1)*Number.

## Finds Factorial of a Number using while loop

#include<stdio.h>
void main()
{
int num, i=1, factorial = 1;
printf("Enter number: ");
scanf("%d",&num);
if (num < 0)
printf("Error - Negative Number.");
else
{
while(i <= num)
{
factorial *= i;
i++;
}
printf("Factorial of %d: %d", num, factorial);
}
}

Output:

$ cc factorial.c
$ ./a.out
Enter number: 5
Factorial of 5: 120
$ vi factorial.c
[$ ./a.out
Enter number: -3
Error - Negative Number.

## Finds Factorial of a Number using for loop

#include
void main()
{
int num, i=1, factorial = 1;
printf("Enter number: ");
scanf("%d",&num);
if (num < 0)
printf("Error - Negative Number.");
else
{
for(i=1;i <= num;i++)
{
factorial *= i;
}
printf("Factorial of %d: %d", num, factorial);
}
}

Output:

$ cc factorial.c
$ ./a.out
Enter number: 4
Factorial of 4: 24

## Finds Factorial of a Number using Recursive Function

Recursive function is a function which calls itself.

#include <stdio.h>
int factorial(int);
void main()
{
int num, i=1, factorial_val = 1;
printf("Enter number: ");
scanf("%d",&num);
if (num < 0)
printf("Error - Negative Number.");
else
{
factorial_val = factorial(num);
printf("Factorial of %d: %d", num, factorial_val);
}
}
int factorial(int num)
{
if(num > 1)
return (num * factorial(num-1));
else
return 1;
}

Output:

$ cc factorial.c
$ ./a.out
Enter number: 6
Factorial of 6: 720