This is one of the interesting problems I have seen in coding interviews for beginners. The program has a 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 numbers 1 to 100 but when we asked to improve that, he couldn't do 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 to.
Unfortunately, we didn't find anyone who brings a completely new solution to the problem, one of our goals was to find such programmers, who can think out-of-box and can offer creativity to the team.
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 to.
Unfortunately, we didn't find anyone who brings a completely new solution to the problem, one of our goals 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.
Also, basic knowledge of essential data structure is also very important and that's why I suggest all Java programmers join a comprehensive Data Structure and Algorithms course like Data Structures and Algorithms: Deep Dive Using Java on Udemy to fill the gaps in your understanding.
Also, basic knowledge of essential data structure is also very important and that's why I suggest all Java programmers join a comprehensive Data Structure and Algorithms course like Data Structures and Algorithms: Deep Dive Using Java on Udemy to fill the gaps in your understanding.
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 numbers 1 to 100 without using a loop. As I said, recursion is the alternative solution because both recursion and iteration allow you to repeat a task. Iteration executes the code inside the loop while in recursion a method keeps calling itself until the base case is reached.Here is a sample code to print 1 to 100 without using a loop in Java. This code uses recursion to solve this problem.
Java Program to print 1 to 100 without using loop - Example
Here is my sample program to print 1 to 100 without using any loop like the for, while, or do-while loop. For the sake of brevity, I have only printed numbers 1 to 10, but you can use the same technique to print as many numbers as you want.However, 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 algorithms, then I suggest you read a good book on Algorithms like the Grokking Algorithms which explains key algorithms with easy-to-understand real-world examples.
Btw, If you are comfortable with recursion and struggle to write recursive algorithms, then I suggest you read a good book on Algorithms like the Grokking Algorithms which explains key algorithms with easy-to-understand real-world examples.
Printing 1 to 100 in Java without using a loop - Example
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 an iterative algorithm while the version which uses recursion is known as a recursive algorithm.
Other Java Coding Problems you may like to explore
Thanks for reading this article so far. If you like this article then please share it with your friends and colleagues. If you have any questions, feedback, or suggestion then please drop a comment.
Other Java Coding Problems you may like to explore
- How to print Fibonacci series in Java (solution)
- How to calculate the square root of a given number in Java? (solution)
- How to remove duplicate elements from the array in Java? (solution)
- How to check if a given number is prime in Java (solution)
- How to check if a number is binary in Java? (algorithm)
- How to calculate the Area of Triangle in Java? (program)
- How to find the highest occurring word from a given file in Java? (solution)
- How to check if the 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 count vowels and consonants in a given String in Java? (solution)
- How to transpose a matrix in Java? (solution)
- How to implement a 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 the 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 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 numbers 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)
P. S. - If you are keen to level up your data structure and algorithm skill and looking for a free Udemy course to join then I highly recommend you to check out these 5 free Data Structure and Algorithms courses from Udemy and Coursera to start with.
And lastly one question for you? Which one is your favorite Java coding exercise? Palindrome, Armstrong, Prime number, Fibonacci, Factorial or this one?
8 comments :
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();
}
}
};
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).
@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.
Collection c = (Collection) IntStream.range(1, 101).boxed().sorted((a,b)->a.compareTo(b)).collect(Collectors.toList());
System.out.println(c);
@Mukesh, that's awesome, Java 8 rocks. Even better if you can explain execution flow for fellow reader. Thanks Javin
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();
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);
}
}
Guys Everyone Using Loop Statement Without Any Loop Share The Program
Post a Comment