Recursion Function
Recursion in C
What is Recursion?
Recursion is a process in which a function calls itself directly or indirectly. A function that calls itself is known as a Recursive Function.
To prevent the function from calling itself forever (which causes a "Stack Overflow"), every recursive function must have two parts:
- Base Case: The condition that stops the recursion.
- Recursive Case: The part where the function calls itself with a smaller or simpler input.
Syntax
if (base_condition) {
return; // Stop the recursion
} else {
recursiveFunction(); // Call itself again
}
}
Practical Example: Factorial of a Number
Calculating the factorial of a number ($n!$) is the most classic example of recursion. Note that $5! = 5 \times 4 \times 3 \times 2 \times 1$.
Example: Factorial Function
int factorial(int n) { // 1. Base Case: factorial of 0 or 1 is 1 if (n <= 1) { return 1; } // 2. Recursive Case: n * factorial of (n-1) else { return n * factorial(n - 1); } }
🪞 The Mirror Analogy
Imagine standing between two parallel mirrors. You see an infinite number of reflections of yourself. That is recursion without a Base Case. In programming, we use the Base Case to "break the mirror" so the program knows when to stop and return the final answer.
loop (iteration). Recursion often results in cleaner, shorter code for complex problems (like tree traversal), but loops are generally faster and use less memory.
Executing...
❌ Error:
✅ Output:
// Click Run ▶ to execute
🏋️ Test Yourself With Exercises
Take our quiz on Recursion Function to test your knowledge.
Browse Quizzes »