Print Numbers 1 to 100 in Java Without Loop

  • Last updated Apr 25, 2024

In this tutorial, you will explore an interesting Java code snippet that allows you to print numbers from 1 to 100 without using a loop.

Here's a Java code snippet to print numbers 1 to 100 without using a loop:

public class Example {

   public static void main(String[] args) {
	Example example = new Example();
	example.print(1, 100);
   }

   public void print(int start, int end) {
	if (start <= end) {
	      System.out.print(start + " ");
	      start++;
	      print(start, end);
	}
   }

}

The output of the above code is as follows:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 

In this example, the class contains a main method, which serves as the entry point of the program. Inside the main method, an instance of the Example class is created using the new keyword, assigned to the variable example. The print method is invoked on the example object, passing two arguments: 1 as the starting number and 100 as the ending number. The print method is a recursive method that prints numbers from the start value to the end value. If the start value is less than or equal to the end value, the method performs the following steps:

  • Prints the start value to the console using System.out.print().
  • Increments the start value by one (start++).
  • Calls the print method recursively with the updated start value and the original end value.

The recursion continues until the start value becomes greater than the end value, at which point the method returns and the recursion unwinds.

In summary, this code uses recursion to print numbers from 1 to 100 without utilizing a loop. It starts with the print method, which recursively prints numbers until the desired range is covered.