How to Use Recursion in C: Syntax, Example, and Tips
In C, recursion means a function calls itself to solve smaller parts of a problem. Use
return with a base case to stop the calls and recursive calls to repeat the process.Syntax
A recursive function in C calls itself inside its body. It must have a base case to stop calling itself, or it will run forever and crash. The general syntax looks like this:
return_type function_name(parameters): Defines the function.if (base_condition): Checks when to stop recursion.return base_value;: Returns a value when base case is met.return function_name(smaller_problem);: Calls itself with a smaller problem.
c
int recursiveFunction(int n) { if (n == 0) { return 0; // base case } return recursiveFunction(n - 1); // recursive call }
Example
This example shows how to calculate the factorial of a number using recursion. The factorial of 5 (written 5!) is 5 × 4 × 3 × 2 × 1 = 120.
c
#include <stdio.h> int factorial(int n) { if (n == 0) { return 1; // base case: factorial of 0 is 1 } return n * factorial(n - 1); // recursive call } int main() { int number = 5; printf("Factorial of %d is %d\n", number, factorial(number)); return 0; }
Output
Factorial of 5 is 120
Common Pitfalls
Common mistakes when using recursion include:
- Missing the base case, causing infinite recursion and program crash.
- Changing the problem incorrectly in recursive calls, leading to wrong results.
- Using recursion for very large inputs without optimization, causing stack overflow.
Always ensure the base case is reachable and the problem size reduces with each call.
c
/* Wrong: Missing base case causes infinite recursion */ int wrongRecursion(int n) { return wrongRecursion(n - 1); // no base case } /* Correct: Base case stops recursion */ int correctRecursion(int n) { if (n <= 0) { return 0; } return correctRecursion(n - 1); }
Quick Reference
Tips for writing recursive functions in C:
- Always define a clear base case to stop recursion.
- Make sure each recursive call works on a smaller or simpler problem.
- Test with small inputs first to avoid infinite loops.
- Use recursion only when it makes the problem simpler or clearer.
Key Takeaways
Recursion in C means a function calls itself with a smaller problem.
Always include a base case to stop the recursive calls.
Each recursive call should move closer to the base case.
Without a base case, recursion causes infinite loops and crashes.
Use recursion for problems that can be broken down into similar smaller problems.