javaloopslogic

How do you print the sequence one 1, then two 2, three 3, ... n ns?


Write a program that prints a part of the sequence:

1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 ...

(the number is repeated as many times, to what it equals to).

I've used two for loops, however, I can't get 1 to print once, 2 to print twice, instead, I get

1 2 3 4 5 6 1 2 3 4 5 6, etc.

Solution

  • You need two for loops for this.

    for (int i = 0; i <= 5; i++) { // This will loop 5 times
        for (int j = 0; j < i; j++) { //This will loop i times
            System.out.print(i);
        }
    }