How to print 1 to 100 without using loop in Java

This is one of the interesting problems  I have seen on coding interviews  for beginners. The program has surprise element by saying that you need to print 1 to 100 without using a loop e.g. for, forEach or enhanced for loop. This brings out some innovative solutions from candidates which tell a lot about their approach, knowledge, and attitude. I remember, asking this question during campus recruitment to at least 5 candidates. The first one took 5 minutes to think and then come up with the brute force way where he just copies pasted 100 System.out.println() and printed number 1 to 100 but when we asked to improve that, he couldn't too that. Unfortunately, he didn't think that recursion can replace an iterative algorithm without using a loop.

The second candidate was more talented and had good knowledge of computer fundamentals, he straight away brings the recursion in place and put the second solution described in this article. We ask this question to 3 more candidates and they took a lot of time to come up with a recursive solution which we are looking forward.

Unfortunately, we didn't find anyone who brings a completely new solution to the problem, one of our goal was to find such programmers, who can think out-of-box and can offer creativity to the team. At last, we end up hiring the second guy who was good at computer fundamentals and data structure and algorithms. Good for us, he turns out to be a star developer in our team and reinforced our belief in hiring someone with good knowledge of basics and coding skills always pays off.



How to print 1 to 100 without using loop in Java

Now, let's shift our focus to the problem in hand, how are you going to print number 1 to 100 without using a loop. As I said, recursion is the alternative solution because both recursion and iteration allows you to repeat a task. Iteration execute the code inside loop while in recursion a method keep calling itself, until base case is reached.




Java Program to print 1 to 100 without using loop 

Here is my sample program to print 1 to 100 without using any loop e.g. for, while or do-while loop. For the sake of brevity, I have only printed number 1 to 10, but you can use the same technique to print as many numbers you want. Though, you might be careful because I have never tested a variable arguments method with more than 10 arguments.

Btw, If you are comfortable with recursion and struggle to write recursive algorithm,  then I suggest you to read a good book on Algorithms e.g. Grokking Algorithms which explains key algorithms with easy-to-understand real world example.

How to print 1 to 100 without using loop in Java


Printing 1 to 100 in Java without using a loop.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;


/**
 * Java Program to print 1 to 100 without using loop
 * 
 * @author WINDOWS 8
 */

public class Test {

    public static void main(String args[]) {
        
        System.out.println("1st way to print 1 to 100 without loops");
        usingSysOut();
        
        System.out.println("2nd way to print 1 to 100 without using loops");
        usingSysPrint();
        
        System.out.println("3rd way to print 1 to 100 without loops");
        usingRecursion(10);
       
    }
        
    
    public static void usingSysOut(){
        System.out.println(1);
        System.out.println(2);
        System.out.println(3);
        System.out.println(4);
        System.out.println(5);
        System.out.println(6);
        System.out.println(7);
        System.out.println(8);
        System.out.println(9);
        System.out.println(10);
    }
    
    public static void usingSysPrint(){
        System.out.printf("%s%n%s%n%s%n%s%n%s%n%s%n"
                + "%s%n%s%n%s%n%s%n", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
    }
    
    public static void usingRecursion(int number){
        if(number > 1){
            usingRecursion(number-1);
        }
        System.out.println(number);
    }
   
}

Output
1st way to print 1 to 100 without loops
1
2
3
4
5
6
7
8
9
10
2nd way to print 1 to 100 without using loops
1
2
3
4
5
6
7
8
9
10
3rd way to print 1 to 100 without loops
1
2
3
4
5
6
7
8
9
10



That's all about how to print 1 to 100 without using a loop in Java. The general rule of thumb is that most of the things which can be done using a loop can also be done using recursion. The loop version of the algorithm is known as iterative algorithm while the version which uses recursion is known as a recursive algorithm.

Further Learning
Algorithms and Data Structures - Part 1 and 2
Java Fundamentals, Part 1 and 2
Cracking the Coding Interview - 189 Questions and Solutions


Other Java Coding Problems you may like to explore
  • How to count vowels and consonants in given String in Java? (solution)
  • How to transpose a matrix in Java? (solution)
  • How to implement binary search using recursion in Java? (solution)
  • How to reverse a String in place in Java? (solution)
  • Java Program to print Prime numbers from 1 to 100? (program)
  • How to implement Linear Search in Java? (solution)
  • How to find largest prime factors of a given integer in Java? (program)
  • How to reverse words in a given String in Java? (solution)
  • How to find all prime factors of a number in Java? (solution)
  • How to check if two given Strings are Anagram in Java? (solution)
  • How to generate prime numbers up to 100 using Sieve of Eratosthenes Algorithm(program)
  • How to remove duplicate characters from String in Java? (solution)
  • How to check if a year is a leap year in Java? (solution)
  • How to find the square root of a number without using a library function in Java? (program)
  • How to remove duplicate elements from the array in Java? (solution)
  • How to check if given number is prime in Java (solution)
  • How to check if a number is binary in Java? (algorithm)
  • How to calculate Area of Triangle in Java? (program)
  • How to print Fibonacci series in Java (solution)
  • How to calculate the square root of a given number in Java? (solution)
  • How to find the highest occurring word from a given file in Java? (solution)
  • How to check if given String is palindrome or not in Java? (solution)
  • How to check if two rectangles intersect with each other in Java? (solution)
  • How to find all permutations of a given String in Java? (solution)
  • How to check if a String contains duplicate characters in Java? (solution)
  • How to calculate the sum of all elements of an array in Java? (program)
  • How to reverse an array in place in Java? (solution)
  • How to print prime number up to a given number in Java? (solution)
  • How to find if given Integer is Palindrome in Java? (solution)
  • How to calculate the average of all numbers of an array in Java? (program)
Thanks for reading this article so far. If you like this article then please share with your friends and colleagues. If you have any question, feedback or suggestion then please drop a comment. 

8 comments :

LionelH said...

Hiding recursion using threads:

public void print1to100() {
new Thread(printNum).start();
}
private Object lock = new Object();
int i = 1;
final Runnable printNum = new Runnable() {
@Override
public void run() {
synchronized (lock) {
Log.d(TAG, "run: " + i);
i++;
}
if (i<=100) {
print1to100();
}
}
};

Anonymous said...

What about IntStream.iterate(1, i -> i + 1).limit(100).forEach(System.out::println)? I'd agree that recursion is surely good answer, but for greater number it can result in StackOverflowError (19735 on my machine).

Javin Paul said...

@Anonymous, this is a good answer because it shows that candidate is familiar with Java 8 stream and new coding style. The purpose for the question was to check computer fundamentals in terms of iterative vs recursive algorithms but sometime it tells other things as well, which surely count.

mukesh baidwan said...

Collection c = (Collection) IntStream.range(1, 101).boxed().sorted((a,b)->a.compareTo(b)).collect(Collectors.toList());
System.out.println(c);

Javin Paul said...

@Mukesh, that's awesome, Java 8 rocks. Even better if you can explain execution flow for fellow reader. Thanks Javin

Alexei Kaigorodov said...

new Runnable() {
int num=1;
@Override
public void run() {
System.out.println(num);
if (num++<100) {
try {
ForkJoinPool.commonPool().submit(this).get();
} catch (Exception e) {
}
}
}
}.run();

Anonymous said...

public class PrintOneToHundred {

public static void main(String arg[]) {
printNum(1);


}

public static void printNum(int n) {
if (n <= 100) {
System.out.println(n);
printNum2(n + 1);
}
}

Anonymous said...

Guys Everyone Using Loop Statement Without Any Loop Share The Program

Post a Comment