Basic Recursion: Print 1 to N
Printing numbers from $1$ to $N$ is one of the simplest recursive exercises. It illustrates how we track a loop counter inside function parameters instead of relying on a standard for or while loop.
The recursive function signature is:
print1ToN(i, n)
We invoke the function initially with $i = 1$. In each recursive step, we print $i$ and call `print1ToN(i + 1, n)` to increment our virtual loop counter.
- Base Case:
i > n. Once $i$ exceeds $n$, we return to prevent infinite loops. - Recursive Step: Increment $i$ by $1$ and call the function again.
Complexity Analysis
Time Complexity: O(N)
The function makes exactly $N+1$ recursive calls to print numbers from 1 to N.
Space Complexity: O(N)
At the deepest recursion level, there are $N+1$ stack frames concurrently on the Call Stack. Thus, auxiliary space is linear, $O(N)$.