Print n to 1
Problem Link
Print N to 1 Without Loop – GeeksforGeeks
Problem: Print N to 1 Without Loop
Problem Statement
Given a number N, print numbers from N to 1 in decreasing order using recursion only. You are not allowed to use loops like for, while, etc.
Examples
Example 1
Input: N = 5
Output: 5 4 3 2 1
Example 2
Input: N = 3
Output: 3 2 1
Constraints
1 <= N <= 10⁴
Intuition
We are asked to simulate a decreasing loop using recursion.
To print from N down to 1, we can directly print N, and then recursively call the function with N - 1.
This is a pre-order recursion, where the print happens before the recursive call.
Approach
-
Define a recursive function
printDecreasing(int N). -
Base case: if
N == 0, return. -
Print the current value
N. -
Recursively call the function with
N - 1.
Code (Java)
class Solution {
public void printNos(int N) {
if (N == 0) return;
System.out.print(N + " ");
printNos(N - 1);
}
}
Time and Space Complexity
-
Time Complexity:
O(N)- We make one recursive call per value from N to 1.
-
Space Complexity:
O(N)- Due to the recursive call stack.
Dry Run
Input: N = 4
Function call trace:
-
printNos(4)→ prints 4 → callsprintNos(3) -
printNos(3)→ prints 3 → callsprintNos(2) -
printNos(2)→ prints 2 → callsprintNos(1) -
printNos(1)→ prints 1 → callsprintNos(0) -
printNos(0)→ base case → return
Output: 4 3 2 1
Conclusion
This problem is a simple demonstration of how recursion can replace loops to print sequences in reverse. It reinforces understanding of recursive flow and base conditions.