Java Program to Print 1 to 100 Without Using Loop

In this post, we will learn to code the Java Program to Print 1 to 100 Without Using Loops. Let’s understand How to print 1 to 100 without using loop in Java Programming Language.

Java Program to Print 1 to 100 Without Using Loop

We can achieve the desired result of printing 1 to 100 without a loop by using the concept of recursion and recursive functions.

import java.util.*;

public class Main{
    
    public static void printFrom1To100(int N){
      // Base Condition
        if(N == 100){
            System.out.println(100);
            return;
        }
        System.out.print(N+" ");
        printFrom1To100(N+1);
    }
    
    public static void main(String[] args){
        
      printFrom1To100(1);
        
    }
    
}

Output

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

How Does This Program Work ?

In this program, we used the concept of Recursion and we created a recursive function to print from 1 to 100 without using loop.

    public static void printFrom1To100(int N){
      // Base Condition
        if(N == 100){
            System.out.println(100);
            return;
        }
        System.out.print(N+" ");
        printFrom1To100(N+1);
    }

We have created a recursive function printFrom1To100() with the base condition if N is equal to 100 then we print 100 and return. For every N value, we print the value and then call the recursive function with the value N+1 till N becomes 100.

We call the function from the main function with the initial passing value of N as 1.

    public static void main(String[] args){
        
      printFrom1To100(1);
        
    }

So, the program executes and the recursive function is called with initial value 1.

Then, in the function, N is not equal to 100. i.e. N = 1. so, the code then prints the value 1 and then calls the function with the value N+1 i.e. N=2.

Then, N=2, and N is not equal to 100. Again we print the value 2 and then call the function with the value N+1 i.e. 3. Similarly this goes on till N becomes 100.

When N = 100, the Base condition is fulfilled, and then the function prints the value of 100 and returns from the function.

This is the Java Program to Print 1 to 100 Without Using Loop.

Conclusion

I hope after going through this post, you understand Java Program to Print 1 to 100 Without Using Loop.
If you have any doubt regarding the topic, feel free to contact us in the comment section. We will be delighted to help you.

Also Read:

Leave a Comment

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