while

Summary

A while loop is used to repeatedly execute code as long as a given condition is true.

Syntax

while (condition)
    statement;

Parameters

condition
A valid expression that must be true for the while loop's statement to be executed.
statement
The statement to execute. In order to execute a group of statements, use a block.

Description

The while loop will repeatedly execute its statement for as long as its condition evaluates to true.

1
2
int i = 0;
while (i < 5) ++i;

In the above code, the i variable is incremented as long as it remains below 5. Therefore, at the end of the while loop, the value is 5.

Skipping Loop Iterations

We can skip while loop iterations using the continue statement. When the continue keyword is encountered, the current loop iteration ends, the while loop's condition is checked, and, if the condition evaluates to true, the next loop iteration will begin.

For example, we can create a while loop to count to 5. However, if we want to skip the number 3, we can use a continue statement if the number equals 3:

1
2
3
4
5
6
7
8
9
10
11
12
13
import System;
 
int i = 0;
while (i < 5) {
    ++i;
     
    //Skip to the next iteration if 'i' equals 3
    if (i == 3) {
        continue;
    }
     
    Console.log(i);
}

If you are using nested while loops, and want to skip to the next iteration for a specific while loop, use labels.

Terminating a while Loop

Be careful to ensure that the while loop's condition evaluates to false at least once; otherwise, it will result in an infinite loop.

A while loop can be explicitly terminated via the break statement.

For instance, we can create an infinite loop by providing a condition that is always true to the while loop, but we can immediately exit the loop using the break keyword:

1
2
3
while (true) {
    break; // Exit immediately to avoid infinite loop
}

If you have nested while loops and wish to terminate a specific loop, use labelled statements.

See Also

Share

HTML | BBCode | Direct Link