Commit 582f3aa
committed
feat: Add FactorialProgram with recursive factorial calculation
WHAT the code does:
- Defines a `FactorialProgram` class to compute factorial of a number using recursion.
- `factorial(int n)`:
- **Base case**: if `n == 1`, prints `"Factorial(1) = 1"` and returns 1.
- **Recursive case**: prints current formula (`n * Factorial(n-1)`) and recursively calls `factorial(n-1)`.
- `main()` calls `factorial(7)` and prints the result.
WHY this matters:
- Demonstrates **recursion** in Java with factorial, a classic example.
- Shows **base case and recursive case structure**.
- Helps understand how recursive calls expand and collapse during execution.
HOW it works (factorial(7)):
1. Prints: `Factorial(7) = 7 * Factorial(6)`.
2. Calls `factorial(6)` → prints `Factorial(6) = 6 * Factorial(5)`.
3. Continues until `Factorial(1) = 1`.
4. Call stack unwinds, multiplying results → `5040`.
Tips & gotchas:
- Factorial grows very fast — `int` will overflow beyond 12! → use `long` or `BigInteger` for larger inputs.
- No check for `n <= 0` → negative or zero input leads to infinite recursion or incorrect results.
- Printing inside recursion is useful for learning but should be removed in production for efficiency.
Use-cases:
- Educational demo for **recursion basics**.
- Useful in algorithm teaching (factorials, Fibonacci, recursion patterns).
- Foundation for more advanced recursion problems.
- Can be adapted for iterative factorial implementations to compare performance.
Short key: algo-factorial-recursion-trace.
Signed-off-by: https://github.com/Someshdiwan <[email protected]>1 parent d6285d5 commit 582f3aa
File tree
1 file changed
+13
-14
lines changed- Section10Methods/RecurssionPractice/src
1 file changed
+13
-14
lines changedLines changed: 13 additions & 14 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | 1 | | |
2 | 2 | | |
3 | 3 | | |
4 | | - | |
5 | | - | |
6 | | - | |
7 | | - | |
8 | | - | |
9 | | - | |
10 | | - | |
11 | | - | |
12 | | - | |
13 | | - | |
14 | 4 | | |
15 | | - | |
16 | | - | |
| 5 | + | |
17 | 6 | | |
18 | 7 | | |
19 | 8 | | |
20 | 9 | | |
21 | 10 | | |
22 | 11 | | |
23 | | - | |
24 | | - | |
| 12 | + | |
| 13 | + | |
| 14 | + | |
| 15 | + | |
| 16 | + | |
25 | 17 | | |
26 | 18 | | |
27 | 19 | | |
| 20 | + | |
| 21 | + | |
| 22 | + | |
| 23 | + | |
| 24 | + | |
| 25 | + | |
| 26 | + | |
0 commit comments