Further For Loops

Statements are optional

Each of the three statements in a for loop declaration are optional (initialisation, continue condition and increment), provided the semi-colons are left in place. It's therefore valid to write code as follows

for (; ; ) {
    //code here (which must break)
}
In order to exit a loop of this format, the break keyword must be used

Multiple variables

Multiple variables of the same type can be declared, and incremented.

This can be useful if the variables should only be in scope inside the loop - the following example to show factorial values uses two variables:

for (long number = 1, factorial = 1; number < 15; number++, factorial *= number ) {
    System.out.println(number +": "+factorial);
}
Note that the initialisation and increment statements are each separated by a comma, and the data type is only declared once.

Task

Write a loop which outputs the numbers increasing one at a time from 0 to 100, whilst simultaneously counting from 200 to 0, two at a time. The output should appear as follows:

0: 200
1: 198
2: 196
etc.
The only variables used should be declared in the 'initialisation' part of the for loop, and calculations should only take place inside of the 'increment statement' component of the loop.

Task 2

Write another loop which outputs the numbers from one to 60, alongside the corresponding value of the column in a binary number (working from right to left). The output should be as follows:

1: 1
2: 2
3: 4
4: 8
5: 16
6: 32
7: 64
8: 128
9: 256
etc.
Again no calculations should take place between the braces for the loop. Verify that the values output are as expected.