For-loops

General Form

For-loops are probably the most commonly used loop statement.  The general form of a for-loop is as follows.

for (init_expr; bool_expr; post_expr1, post_expr2, ...) {
    ...
}

Every for-loop can be written alternatively with a while loop.  An equivalent general form is below.

init_expr;
while(bool_expr) {
    ...
post_expr1;
post_expr2;
...
}

Usage

As illustrated in the example below, you can leave the expressions empty but you must include the semicolons.  This loop is an infinite loop and does nothing except spin.

for ( ; ; ) {
    ;
}

The code below simulates a while-loop that counts from 0 to 9.

int i = 0;
for (; i < 10; ) {
    System.out.printf("%d ", i);
    i++;
}

Below is a code fragment does the same thing as above, it counts from 0 to 9.

for (int i = 0; i < 9; i++) {
    System.out.printf("%d\n", i);
}

The example below uses multiple post expressions to increment a lower bound variable and decrement an upper bound variable.

for (int i = 0, j = 10; i < j; i++, j--) {
    System.out.println("%d %d\n", i, j);
}

The code below counts the number of even numbers between an upper and lower bound (exclusively).

int a = ...
int b = ...

int numEven = 0;
for (int i = a + 1; i < b; i++) {
    if (i % 2 == 0) {
        numEven++;
    }
}
System.out.println("Number of even numbers: %d\n", numEven);

© 2017, Eric. All rights reserved.