Write a java program to print 1 to 100 numbers without using loop. This problem is very interesting and tricky for beginners. You have to think how you can print numbers from 1 to 100 without using for and while loop in your code.
We can easily solved this problem using loop (for and while loop). But suppose you don’t have to use loop to print the numbers.
We can easily print the numbers from 1 to 100 using recursion. In that case, we don’t have to use any for and while loop.
If you are not familiar with recursion then check my previous tutorial on recursion.
Java Program to Print 1 to 100 Numbers without using Loop
Let’s write a java code to print 1 to 100 without using loop. In this code example, we are going to use recursion to solve this problem.
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 |
/** * Java Program to Print Numbers from 1 to 100 without using loop */ public class PrintNumbers { public static void printNum(int num) { //If numbers is less than or equal to 100 if(num <= 100) { System.out.print(num + " "); //Increment and call printNum recursively printNum(num+1); } } public static void main(String[] args) { //Declare variable and assign a value 1 int n = 1; //call printNum method printNum(n); } } |