Sunday, 2 October 2016

How to Print 1 to 100 without using Loop and Recursion in Java?

For printing numbers between a range can easily be done using loops or recursion. But if the question is to print the numbers without using loop or recursion in Java then some people say it is impossible to print and some people will think how to solve this without loop and recursion.

But, there are very few people who knows the beauty of BitSet class of util package in Java. We can use this BitSet class to print numbers between a range (0 <= n <= 841) without using loop or recursion.

Since the range 1 to 100 falls under the range, so we can utilize BitSet class of util package to print 1 to 100 without using loop and recursion.


  /*
  * Print 1 to 100 without using loop and recursion
  */
 public static void print1To100(){


BitSet bit = new BitSet(0);

bit.set(1, 100+1);
String set = bit.toString();
set = set.replaceAll(",", "\n");
        
System.out.println(set.substring(1, set.length()-1));
 }


Output -

1
2
...
100

No comments:

Post a Comment