๐ C Recursion – Functions Calling Themselves
In C, recursion is a programming technique where a function calls itself to solve a smaller version of the original problem. It’s useful for problems that can be broken down into sub-problems, like factorials, Fibonacci numbers, and more.
๐น Key Concepts of Recursion
- Every recursive function needs a base case to stop calling itself.
- Each recursive call should work on a smaller/simpler problem.
- Too many recursive calls without a base case will cause a stack overflow.
๐ Example 1: Factorial Using Recursion
This function calculates the factorial of a number by calling itself.
#include <stdio.h> int factorial(int n); int main() { int num = 5; printf("Factorial of %d is %d\n", num, factorial(num)); return 0; } int factorial(int n) { if (n == 0) { return 1; // Base case } return n * factorial(n - 1); // Recursive call }
๐ Example 2: Fibonacci Series Using Recursion
This function returns the nth Fibonacci number recursively.
#include <stdio.h> int fibonacci(int n); int main() { int i; for (i = 0; i < 10; i++) { printf("%d ", fibonacci(i)); } return 0; } int fibonacci(int n) { if (n == 0) return 0; if (n == 1) return 1; return fibonacci(n - 1) + fibonacci(n - 2); // Recursive calls }
โ ๏ธ When Not to Use Recursion
- For very deep or infinite recursion (you may run out of memory).
- When an iterative solution is simpler and more efficient.
๐ฏ Summary
- Recursion = function calling itself with a smaller problem.
- Always define a clear base case.
- Commonly used in mathematical problems and data structures.
๐ก Practice Challenge
Try writing your own recursive functions for sum of digits, power calculation, or reverse a number. Recursion is a magical tool once you get the hang of it!