Search⌘ K
AI Features

Using while and do-while Loops

Explore how to use while and do-while loops in Dart to control program flow. Understand loop structures, apply sentinel values for input processing, and learn to avoid infinite loops by properly updating control variables.

When we use the word "while" in everyday language, we often relate it to time and ongoing events. For instance, stating that we are reading a book while a sibling gets ready indicates that the act of reading continues as long as the other event is taking place.

A while loop in Dart behaves similarly. It evaluates a boolean condition and repeatedly executes a specific block of code as long as that condition evaluates to true.

The while loop

Before applying the loop to a real scenario, let us understand its structural components.

Structure of the while loop

We construct a while loop using the while keyword, followed by a condition wrapped in parentheses, and finally a block of code enclosed in curly braces.

Dart
while (condition) {
// Code to execute repeatedly
}

The program evaluates the condition first. If the condition is true, the program executes the code block and then checks the condition again, repeating this cycle until the condition becomes false.

Flow chart to while loops
Flow chart to while loops

Let us look at how we can use a runnable while loop to print numbers sequentially from 1 to 10.

Dart
void main() {
var count = 1;
while (count <= 10) {
print(count);
count += 1;
}
}
    ...