while loops

LPC's while loop is identical to that provided by C. Syntax is as follows:

while (expression)
    statement;

where statement may be replaced by a block of statements surrounded by curly brackets:

while (expression) {
    statement1;
    statement2;
    ...
}

The statements inside the body of the while loop will be executed repeatedly as long as the test expression evaluates to non-zero, however, the the test expression is only tested at the top of the loop. If the test expression is zero prior to the execution of the loop, the loop will not be executed, and execution continues after the loop. If you want the loop to execute at least once, use a do while loop. A break ; staement in the body of the loop will terminate the loop, skipping immediately to the first statement after the loop. A continue ; expression will go back to the top of the loop, check the test expression, and restart from the top as if the bottom of the loop had been reached, skipping the remainder of the statements in the loop.

int test(int limit) {
    int total = 0;
    int j = 0;
    while (j < limit) {
        if ((j % 2) != 0)
            continue;
        total += j;
        j++;
    }
    return total;
}

The result of this code fragment will be to sum all of the even numbers from 0 to limit - 1.

See also the summary of loops .


Tim Hollebeek

Beek @ZorkMUD, Lima Bean, IdeaExchange, TMI-2, and elsewhere