A recursive function is a function that calls itself directly or indirectly in its own definition. Recursive functions are often used to solve problems that can be broken down into smaller, similar subproblems. In C, recursive functions follow a specific syntax and require a base case to terminate the recursion.
Syntax:
return_type function_name(parameters) {
// Base case(s)
if (base_case_condition) {
// Return base case value
return base_case_value;
}
// Recursive case(s)
// Perform recursive calls
return recursive_function_call(arguments);
}
return_type: Specifies the data type of the value that the function returns. It can be any valid C data type, including user-defined types.
function_name: This is the name of the recursive function.
parameters: These are the parameters (if any) that the recursive function takes.
Base case(s): These are the conditions under which the recursion stops. The base case(s) ensure that the recursive function eventually reaches a terminating condition to prevent infinite recursion.
Recursive case(s): These are the conditions under which the function calls itself recursively. Recursive cases break down the problem into smaller, similar subproblems until reaching the base case(s).
Return statement: In both the base case(s) and recursive case(s), the function typically returns a value. However, the return type can also be void if the function doesn't return any value.
Example:
#include <stdio.h>
// Recursive function to calculate factorial
unsigned long long factorial(int n) {
// Base case: factorial of 0 is 1
if (n == 0) {
return 1;
}
// Recursive case: n! = n * (n-1)!
return n * factorial(n - 1);
}
int main() {
int num = 5;
unsigned long long result = factorial(num);
printf("Factorial of %d is %llu\n", num, result);
return 0;
}
The factorial function is defined with a return type of unsigned long long to handle large factorial values.
The base case is defined as if (n == 0) which returns 1 when n is 0, as the factorial of 0 is defined as 1.
The recursive case is defined as return n * factorial(n - 1), which recursively calls the factorial function with n - 1 until reaching the base case.
In the main function, factorial is called with an integer argument 5, and the returned value is printed to calculate the factorial of 5.
ADVANTAGES OF RECURSIVE FUNCTION