Print Numbers from 1 to N without using loop in Java

If you want to practice data structure and algorithm programs, you can go through Java coding interview questions.

In this post, we will see how to print numbers from 1 to N without using loop in Java.


Problem

Print number from 1 to N without using any loop.

N=10
Output: 1 2 3 4 5 6 7 8 9 10

Using Recursion

We can use tail recursion to solve this problem.

  • Base case
    • When n <= 0, return
  • call printNumbers recursively with n-1
  • Print number while returning from recursion.
package org.arpit.java2blog;

public class PrintNumbersWithoutLoop {

    public static void main(String[] args) {
        PrintNumbersWithoutLoop pnwl=new PrintNumbersWithoutLoop();
        pnwl.printNumbers(10);

    }

    public void printNumbers(int n)
    {
        if(n<=0)
        {
            return;
        }
        else
        {
            // Recursively call printNumbers
            printNumbers(n-1);
            // Print number while returning from recursion
            System.out.print(" "+n);
        }
    }

}

Output

1 2 3 4 5 6 7 8 9 10

That’s all about how to print Numbers from 1 to N without using loop.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.