Skip to content

Commit 0366936

Browse files
committed
feat: Add PrintNumbersBackward class with recursive countdown
WHAT the code does: - Defines a `PrintNumbersBackward` class that prints numbers in reverse using recursion. - `countBackwards(int n)`: - **Base case**: if `n == 0`, prints `"Done!"`. - **Recursive case**: prints current `n`, decrements it, and calls `countBackwards(n)` again. - `main()` calls `countBackwards(7)` to start the countdown. WHY this matters: - Demonstrates **recursion with a decreasing counter**. - Shows how to build both a **base case** (termination) and **recursive case** (progress). - Useful for teaching recursion flow and call stack behavior. HOW it works: 1. `countBackwards(7)` prints `7` → calls `countBackwards(6)`. 2. Prints numbers down to `1`. 3. At `n == 0`, prints `"Done!"` and recursion terminates. Tips & gotchas: - Works only for non-negative numbers; negative input would recurse infinitely. - Tail recursion optimization is not supported in Java → large `n` may cause `StackOverflowError`. - Could be rewritten iteratively for efficiency in production, but recursion is clearer for learning. Use-cases: - Educational example for recursion basics. - Can be adapted for countdown timers, loops expressed recursively, or reverse iteration problems. - Useful in interviews to demonstrate recursive thinking. Short key: algo-recursive-countdown. Signed-off-by: https://github.com/Someshdiwan <[email protected]>
1 parent 582f3aa commit 0366936

File tree

1 file changed

+2
-3
lines changed

1 file changed

+2
-3
lines changed

Section10Methods/RecurssionPractice/src/PrintNumbersBackward.java

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,10 @@ public static void main(String[] args) {
33
countBackwards(7);
44
}
55
public static void countBackwards(int n){
6-
if(n==0)
7-
{
6+
if(n==0) {
87
System.out.println("Done!");
98
}
10-
else{
9+
else {
1110
System.out.println(n);
1211
n--;
1312
countBackwards(n);

0 commit comments

Comments
 (0)