C Recursion
Syntax
Recursion is a technique in programming where a function calls itself repeatedly to perform a particular task. The syntax for a recursive function in C is:
data_type recursive_function_name(arguments) {
// base case, return a value
if (some condition) {
return some_value;
}
// recursive case, call the function again
recursive_function_name(arguments);
// process results
// return a value
}
Example
To help illustrate the concept of recursion, here is an example of a recursive function that calculates the factorial of a number:
#include <stdio.h>
int factorial(int n) {
if (n == 0) {
return 1;
} else {
return n * factorial(n-1);
}
}
int main() {
int n = 5;
int result = factorial(n);
printf("%d! = %d\n", n, result);
return 0;
}
Output
5! = 120
Explanation
In the above example, the factorial()
function is called recursively to calculate the factorial of a number. The base case for this function is when the input number n
is equal to 0, and the function returns 1. For any input number greater than zero, the function calls itself with n-1
as the argument and multiplies the result with n
. When the base case is reached, the function returns the final result.
Use
Recursion can be used in a variety of ways in C programming, including:
- Traversing hierarchical data structures such as binary trees or linked lists
- Implementing searching algorithms such as binary search
- Generating permutations and combinations of elements
Important Points
- Recursion can lead to stack overflow if not implemented properly, so it is important to have a base case that will eventually be reached to stop the recursion.
- A recursive function should not call itself indefinitely to prevent an infinite loop.
- Recursion can be an elegant solution to some problems, but it may not always be the most efficient solution.
Summary
Recursion is a powerful technique in programming where a function calls itself repeatedly until a base case is reached. A recursive function can be used to solve a variety of problems, such as calculating factorials or traversing data structures. However, it is important to implement recursion properly with a clear base case to prevent stack overflow and infinite loops.