Print 1 to 100 Without Loop in Java

Java Program to Print 1 to 100 without using a loop. To solve this problem, we can use recursion techniques.

A method that contains a call to itself is called the recursive method. A technique of defining the recursive method is called recursion. The recursive method allows us to divide the complex problem into identical single simple cases that can be handled easily. This is also a well-known computer programming technique: divide and conquer.

In general, programmers use two approaches to writing repetitive algorithms. One approach uses loops i.e. iteration and the other approach uses recursion. Recursion is a repetitive process in which a method calls itself. Some older language does not support recursion. One major language that does not support is COBOL.

A recursive method must have at least one exit condition that can satisfy. Otherwise, the recursive method will call itself repeatedly until the runtime stack overflows. To prevent infinite recursion generally if-else (or similar approach) can be used where one branch makes the recursive call and other doesn’t.

Java Program to Print 1 to 100 without using loop

public class KnowProgram {
  public static void main(String[] args) {

    // variable
    int n = 100;
    
    // method call
    System.out.println("Displaying from 1 to 100: ");
    display(n);
  }

  // recursive method
  public static void display(int n) {
     if(n > 1)
       display(n-1);
     System.out.print(n+" ");
  }

}

Output:-

Displaying from 1 to 100:
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

// recursive method
public static void display(int n) {
  if(n > 1)
    display(n-1); // base condition
  System.out.print(n+" ");
}

In the display() method, the base condition is:- when n is greater than 1 then call display(n-1).

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

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