Summary: In this tutorial, you’ll learn how to use the Dart do while loop to execute statements repeatedly as long as a condition is true.
Introduction to the Dart do-while statement #
The Dart do while statement executes statements as long as a condition is true. Here’s the syntax of the do while statement:
do
{
// statements
} while (expression);Code language: Dart (dart)Different from the while statement, the do while statement evaluates the expression at the end of each iteration. Therefore, it’s called a posttest loop.
The do while statement always executes the first iteration, whether the result of the expression is true or not. And it executes the statement repeatedly as long as the expression is true.
The following flowchart shows how the Dart do while statement works:
Dart do while statement examples #
The following examples illustrate how the do while statement works.
1) Simple Dart do-while statement example #
The following example uses the do while statement to display five numbers from 1 to 5:
void main() {
int number = 0;
do {
number++;
print(number);
} while (number < 5);
}
Code language: Dart (dart)Output:
1
2
3
4
5Code language: Dart (dart)How it works.
First, declare the number variable and initialize its value to 0:
int number = 0;Code language: Dart (dart)Second, increase the number by one and display it inside the do while block:
do {
number++;
print(number);
} while (number < 5);Code language: Dart (dart)Repeat this step as long as the number is less than 5. Because the number starts at 1, the do while statement executes exactly five times.
2) Using the do-while statement to display odd numbers #
The following program uses a do while loop statement to display odd numbers:
void main() {
int number = 0;
do {
if (number % 2 == 1) {
print(number);
}
number++;
} while (number < 10);
}Code language: Dart (dart)First, declare the number variable and initialize its values to zero:
int number = 0;Code language: Dart (dart)Second, use a do while loop to iterate from 1 to 10 and display only odd numbers. An even number is a number that has a remainder of 1 upon division by 2 (number % 2 == 1):
do {
if (number % 2 == 1) {
print(number);
}
number++;
} while (number < 10);Code language: Dart (dart)Summary #
- Use the
do whilestatement to execute a block of code repeatedly as long as a condition is true.