Summary: in this tutorial, you’ll learn how to use the Dart while
statement to execute statements repeatedly as long as a condition is true
.
Introduction to the Dart while statement
The while
statement evaluates a Boolean expression and executes statements repeatedly as long as the result of the expression is true
.
The following illustrates the syntax of the while
statement:
while (expression)
{
// statement
}
Code language: Dart (dart)
In this syntax:
The expression
is a Boolean expression that evaluates to true
or false
.
The while
statement evaluates the expression
. If the result is true
, it’ll execute statements inside the curly braces.
The while
statement evaluates the expression
before each iteration. And it’ll execute statements again and again as long as the result of the expression is true
.
If the result of expression
is false
, the while
statement exits and passes the control to the statement after it.
Therefore, you need to change some variables inside the body of the while
statement to make the expression
false
at some point. Otherwise, you’ll have an indefinite loop. An indefinite loop executes the statements repeatedly until the program crashes.
Since the while
statement checks the expression
at the beginning of each iteration, it is often called a pretest loop.
The following flowchart illustrates how the Dart while
statement works.
Dart while statement examples
Let’s take some examples of using the while
statement.
1) Simple Dart while statement example
The following example uses the while
loop statement to display five integers from 1 to 5:
void main() {
int current = 0;
while (current < 5) {
current++;
print(current);
}
}
Code language: Dart (dart)
Output:
1
2
3
4
5
Code language: Dart (dart)
How it works.
First, declare a current
variable and initialize its value to zero.
Second, enter the while
loop because the following expression is true
:
current < 5
Code language: Dart (dart)
Third, increase the current
by one and display it; The while statement repeats this step as long as until the current
is 5.
2) Using the Dart while statement to display even numbers between 0 and 10
The following program uses a while
loop to display all even numbers from 0 to 10:
void main() {
int number = 0;
while (number < 10) {
if (number % 2 == 0) {
print(number);
}
number++;
}
}
Code language: Dart (dart)
Output:
0
2
4
6
8
How it works.
First, declare a variable number
and initialize its value to zero:
int number = 0;
Code language: Dart (dart)
Second, execute the loop as long as the number is less than 10. Inside the loop, we use the if
statement to display the number if it is even.
while (number < 10) {
if (number % 2 == 0) {
print(number);
}
number++;
}
Code language: Dart (dart)
Note that an even number is a number that has a remainder of 0 upon division by 2.
Summary
- Use the
while
statement to execute statements repeatedly as long as a condition istrue
.