Print n to 1


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


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

  1. Define a recursive function printDecreasing(int N).

  2. Base case: if N == 0, return.

  3. Print the current value N.

  4. 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


Dry Run

Input: N = 4

Function call trace:

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.