Do-while Loops

The general form of the do-while loop is as follows.

do {
    ...
} while (bool_expr);

Here, the body of the while-loop is executed at least once and continues to be executed until the boolean expression evaluates to false.

Example

Again, we count the number of even numbers between a and b exclusively.

int numEven = 0;
int a = kb.nextInt();
int b = kb.nextInt();

int i = a + 1;
if (i >= b)
    return;

do {
    if (i % 2 == 0) {
        numEven++;
    }
    i++;
} while(i < b);

© 2017, Eric. All rights reserved.