Commit dc5bde9
committed
feat: Add Recursion program to demonstrate simple recursive number printing
WHAT the code does:
Defines a Recursion class with:
- fun(int n): recursive method that decrements n until reaching 0, then prints numbers as the call stack unwinds.
- main(): calls fun(9), which prints numbers from 1 to 9 in ascending order.
WHY this matters:
Demonstrates fundamental recursion:
- A base condition (n > 0) ensures termination.
- Recursive call fun(n - 1) reduces the problem size.
- Printing after the recursive call leverages the call stack to reverse the order.
Illustrates how recursion naturally handles repetitive tasks without explicit loops.
HOW it works:
fun(9) calls fun(8), which calls fun(7), and so on until n = 0.
At n = 0, recursion stops.
As calls return, each prints its value of n.
Final output: 1 2 3 4 5 6 7 8 9.
Tips and gotchas:
Recursion depth is limited by stack size; very large n may cause StackOverflowError.
Printing before the recursive call would reverse the output order (9 down to 1).
Recursion is elegant for conceptual problems but less efficient than iteration for simple loops.
Always ensure a base case to prevent infinite recursion.
Use-cases:
Educational demonstration of recursion mechanics in Java.
Building block for recursive algorithms such as factorial, Fibonacci, and tree traversal.
Foundation for understanding how call stacks work and how order of execution affects results.
Short key: class-recursion print-numbers ascending-order.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent aef2d5d commit dc5bde9
1 file changed
+7
-10
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | | - | |
2 | | - | |
| 1 | + | |
3 | 2 | | |
4 | | - | |
5 | | - | |
| 3 | + | |
6 | 4 | | |
7 | | - | |
| 5 | + | |
8 | 6 | | |
9 | 7 | | |
10 | | - | |
11 | | - | |
12 | | - | |
13 | | - | |
14 | | - | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
| 11 | + | |
0 commit comments