712048. Print N to 1 without loop

Easy

Print N to 1 without Loop

Summary

This problem requires you to print numbers from N to 1, but without using a loop. The key concept involved is recursion, which allows us to break down the problem into smaller sub-problems and solve them in a similar way.

Detailed Explanation

To solve this problem, we will use recursion to print the numbers from N to 1. Here's how it works:

  • We start by printing the number N.
  • Then, we call the same function recursively with N-1 as the input.
  • This process continues until we reach 1, at which point we stop calling the function.

Here's a step-by-step breakdown of the solution:

PrintN(int n) {
    if (n > 0) {
        PrintN(n - 1);
        System.out.println(n);
    }
}

We start by printing the number N. Then, we call the same function recursively with N-1 as the input. This process continues until we reach 1, at which point we stop calling the function.

The time complexity of this solution is O(N), where N is the input number. The space complexity is O(1) because we only use a constant amount of space to store the recursive function call.

Optimized Solutions

Java

View on GeeksforGeeks
public class PrintN {
    public static void printN(int n) {
        if (n > 0) {
            System.out.println(n);
            printN(n - 1);
        }
    }

    public static void main(String[] args) {
        printN(5); // prints 5, 4, 3, 2, 1
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.