C Program to Find Factorial of a Number Using Recursion
Write a C program to find factorial of a number using recursion
- Prompt and read an integer input from the user.
- Check if the number is negative and handle it with an error message.
- Call the recursion factorial() function to compute the factorial for valid input.
- Base case returns 1 for 0 or 1, and the recursion case multiplies n by factorial(n-1).
Example : pgm.c
#include <stdio.h> // Recursion function to calculate factorial int factorial(int n) { if (n == 0 || n == 1) // Base case return 1; else return n * factorial(n - 1); // Recursion call } int main() { int num; printf("Enter a number: "); scanf("%d", &num); if (num < 0) printf("Factorial is not defined for negative numbers.\n"); else printf("Factorial of %d is %d\n", num, factorial(num)); return 0; }
Output :
Enter a number: 5
Factorial of 5 is 120
Factorial of 5 is 120