C Program to Find the Factorial of a Number Using Recursion
Aim:
To write a C program to find the factorial of a given number using a recursive function.
Algorithm:
1. Start the program.
2. Declare an integer variable 'n' for input and 'fact' for storing the factorial.
3. Define a recursive function 'factorial(int n)' that:
- Returns 1 if n is 0 or 1.
- Otherwise, returns n * factorial(n-1).
4. Read a number from the user.
5. Call the recursive function and store the result in 'fact'.
6. Display the factorial.
7. Stop the program.
Program:
#include <stdio.h>
#include <conio.h>
// Recursive function to calculate factorial
int factorial(int n)
{
if(n == 0 || n == 1)
return 1;
else
return n * factorial(n - 1);
}
void main()
{
int n, fact;
clrscr();
printf("Enter a number: ");
scanf("%d", &n);
fact = factorial(n); // Function call
printf("Factorial of %d = %d", n, fact);
getch();
}
Output:
Enter a number: 5
Factorial of 5 = 120
Result:
The program successfully calculates the factorial of a given number using a recursive
function.