JavaRush /Java Blog /Random EN /How to print numbers from 1 to 100 in Java without loops ...

How to print numbers from 1 to 100 in Java without loops and conditions?

Published in the Random EN group
This post is primarily intended for those preparing for interviews. This is where they like to ask these kinds of puzzles. In fact, the task at hand is easier and more logical to solve with cycles and conditions. And we think that any JavaRush student will be able to do this after the fourth level of the Java Syntax quest . But the vast majority of the above methods are designed for those who have already “entered” Java Multithreading . Note: This is about not using loops and conditions directly. In fact, they are implicitly “built into” most of the solutions mentioned. How to print numbers from 1 to 100 in Java without loops and conditions?  - 1
Perhaps you have your own solution to this problem? Share in the comments!

So, method 1: just write it!

Of course, the first thing that comes to a beginner’s mind is direct search. Irrational, but simple and understandable. Exactly the same way we solved problems in the first levels of JavaRush.
System.out.println("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"
);
But, you must admit, it’s somehow boring. Therefore, you can use the second method.

Method 2: use strings and override toString

public static void main(String[] args) {

        Object[] numbers = new Object[100];
        Arrays.fill(numbers, new Object() {    //создаем анонимный класс
            private int count = 0;
            @Override
            public String toString() {
                return Integer.toString(++count);
            }
        });
        System.out.println(Arrays.toString(numbers));

    }
The annotation @Overrideindicates that we are going to override a base class method. In this case we are overriding toString. In fact, this, like almost all of the following solutions, contains loops. These cycles are simply built into the methods used.

Method 3: use recursion

To understand recursion, you need to understand recursion. Recursion, or a function calling itself, is a very interesting topic, and not always immediately understandable. On JavaRush it is covered in the Java Collections quest (for completeness), but in fact it can be understood and used (or not used... why - you will find out while studying the topic!) much earlier, immediately after studying loops and conditional jumps.
public class Recursion {

    public void ShowNums(int i) {
    // метод, который печатает

        int x = 1;

// блок try проверяет, достигли ли мы нуля
        try {
            int m = x / i;				// здесь выбрасывается исключение при i = 0
            System.out.println(i);
            i--;
            ShowNums(i);				// а вот и рекурсивный вызов
        }
        catch(ArithmeticException e) {
		// деление на нуль выбрасывает ArithmeticException
            return;					// Останавливается при попытке деления на нуль
        }

    }

     public static void main(String[] args) {

        Recursion r = new Recursion();
        r.ShowNums(100);				// вызов метода со meaningм 100
    }

}
Note:here the output is made not in direct, but in reverse order. Try changing the code so that the numbers are displayed as stated in the condition, that is, from 1 to 100. We are waiting for solutions in the comments!

Method 4: use semaphores

public class To100 {
    public static void main(String[] args) {
        final int max = 100;
        new java.util.concurrent.Semaphore(max) {
            void go() {
                acquireUninterruptibly();
                System.err.println(max-availablePermits());
                go();
            }
        }.go();
    }
}
Semaphores are a synchronization means for accessing a resource. In Java, semaphores are represented by theSemaphorelibraryjava.util.concurrent.

Method 5: use threads

public class Counter extends Thread{

    private int cnt;

    public Counter(){
        this.cnt = 0;
    }

    private void increment(){
        System.out.println(cnt++);
        try{
            Thread.sleep(1000);
        }catch(Exception e){}
        increment();
    }

    public void run(){
        increment();
    }

    public static void main(String[] args) throws Exception{
        Counter cntr = new Counter();
        cntr.start();
        cntr.join(100000);
        cntr.interrupt();
        System.exit(0);
    }
}

Method 6: Know your libraries!

Java has a lot of interesting things. For example, class java.util.BitSet. It allows you to create a bit vector whose size changes dynamically. That is, a class object BitSetis a certain ordered set of bits with values true​​or false. Initially all bits are equal false. To store the set, the amount of memory required to store the vector up to the most significant bit that was set or reset in the program is allocated - all bits exceeding it are considered equal false.
public class To100 {
    public static void main(String[] args) {
        String set = new java.util.BitSet() {{ set(1, 100+1); }}.toString();
        System.out.append(set, 1, set.length()-1);
    }
}

Method 7: Use the Vector class

Yes, the vector class is obsolete and is used extremely rarely. Still, why not?
import java.util.Vector;

public class PrintOneToHundered {
  static int i;
  PrintOneToHundered() {}
  public String toString() { return ++i+""; }
  public static void main(String[] args) {
    Vector v1  =new Vector(); v1  .add(new PrintOneToHundered());
    Vector v2  =new Vector(); v2  .addAll(v1 ); v2  .addAll(v1 );
    Vector v4  =new Vector(); v4  .addAll(v2 ); v4  .addAll(v2 );
    Vector v8  =new Vector(); v8  .addAll(v4 ); v8  .addAll(v4 );
    Vector v16 =new Vector(); v16 .addAll(v8 ); v16 .addAll(v8 );
    Vector v32 =new Vector(); v32 .addAll(v16); v32 .addAll(v16);
    Vector v64 =new Vector(); v64 .addAll(v32); v64 .addAll(v32);
    Vector v100=new Vector(); v100.addAll(v64); v100.addAll(v32); v100.addAll(v4);
    System.out.println(v100);
  }
}
Based on materials from Quora
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION