Skip to content

Commit dc5bde9

Browse files
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

File tree

1 file changed

+7
-10
lines changed

1 file changed

+7
-10
lines changed
Lines changed: 7 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,11 @@
1-
public class Recursion
2-
{
1+
public class Recursion {
32
static void fun(int n) {
4-
if (n > 0)
5-
{
3+
if (n > 0) {
64
fun(n - 1);
7-
System.out.println(n);
5+
System.out.print(" "+n);
86
}
97
}
10-
public static void main(String[] args)
11-
{
12-
fun(9) ;
13-
}
14-
}
8+
public static void main(String[] args) {
9+
fun(9) ;
10+
}
11+
}

0 commit comments

Comments
 (0)