A recursive function in C is a function that calls itself in order to solve a problem. It breaks a problem into smaller versions of the same problem until it reaches a simple case, known as the base case, which stops the recursion.
A recursive function generally has two parts
1. Base case: This defines the stopping condition for the recursion.
2. Recursive case: This part breaks down the problem into smaller sub-problems and calls the function itself.
General Structure of Recursive Function:
return_type function_name(parameters) {
if (base_case_condition) {
// Return result (or handle the simplest case)
} else {
// Recursive case (call the function itself)
return function_name(smaller_sub_problem);
}
}
Example: Factorial Program
#include <stdio.h>
int factorial(int n) {
if (n == 0) {
return 1; // Base case
} else {
return n * factorial(n - 1); // Recursive case
}
}
int main() {
int num;
printf("Enter a number: ");
scanf("%d", &num);
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
Explanation:
- The function factorial checks if n is 0. If true, it returns 1 (base case).
- Otherwise, it multiplies n by the factorial of n – 1, recursively calling the factorial function until the base case is reached.