-2

I'm trying to print the following sequence infinitely:

0   100
1    99
2    98
.     .
.     .
.     .
97    3 
98    2
99    1
100   0 
99    1
98    2
97    3
.     .
.     .
.     . 
3     97
2     98
1     99
0     100
.      .
.      .
.      .

However, when I run this, the pattern only prints once.

Here's my code:

public class PrintSequence {
    public static void main(String args[]) {
        int i=0;
        while(true) 
        {
            if(i<=100) {
                System.out.println(i+ "   " + (100-i));    
                i++;
            }

        }

    }
}

The assignment only allows me to use a single loop and a single variable.

2 Answers2

1

There are 2 tricks needed to solve this:

  • Realize that a full cycle from 0,100 back to 0,100 is 200 iterations, then use % remainder operator to write an infinite loop within range 0-199.

  • Use Math.abs()1 to turn a negative number into a positive number.

Here is 2 lines of code that will produce the desired infinite output:

for (int i = 0; ; i = (i + 1) % 200)
    System.out.printf("%-6d%d%n", 100 - Math.abs(100 - i), Math.abs(100 - i));

Explanation

for (;;) is a loop that runs "forever" (infinitely). It is the same as for (; true; ), and the same as while (true), but using for allows keeping int i = 0, the loop, and i = (i + 1) % 200 together in one line of code.

i = (i + 1) % 200 means that when i = 199, the next value is i = 0, starting the sequence all over again, forever iterating through values 0..199.

100 - i makes the sequence 0..199 become 100..-99.

Math.abs(100 - i) makes the sequence become 100..0..99, i.e. the second column of the output.

100 - Math.abs(100 - i) makes the sequence become 0..100..1, i.e. the first column of the output.

printf("%-6d%d%n", ...) makes it print nice in 2 columns.


1) If Math.abs() is not allowed, use a ?: ternary conditional operator instead:
printf("%-6d%d%n", (i < 100 ? i : 200 - i), (i < 100 ? 100 - i : i - 100))

Andreas
  • 154,647
  • 11
  • 152
  • 247
1

You can do it as follows:

public class Main {
    public static void main(String[] args) {
        int i = 0;
        while (true) {
            if (i <= 100) {
                System.out.println(i + "\t" + (100 - i));
                i++;
            } else if (i <= 200) {
                System.out.println((200 - i) + "\t" + (i - 100));
                i++;
            }
            if (i == 200) {
                i = 0;
            }
        }
    }
}

Salient features:

  1. It exactly meets your requirement.
  2. It does not require any library.
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110