do-while
The do-while loop executes a code block once and then will execute it again as long as the given condition is true. The syntax is the following:
do{
// code that will be executed at least once
} while ( condition );
Let's write a program to print the numbers from one to ten using a do-while loop. The flowchart using a do-while loop is:
- We start with a variable i with initial value of 1:
var i = 1
- We will print the value of i then we will increase it by one using ++:
print( i++ )
- We will loop as long as i is less or equals to 10:
i <= 10
Let's run the code in DartPad:
Use a do-while loop to iterate a list
We can also use a do-while loop to iterate each element in a list. Let's write a program to learn how to do it.
Given the next list of cars:
var cars = ['Toyota', 'Mazda', 'Nissan'];
We want to print each of them using a do-while loop. What do we have to do?
- We need a variable with an initial value of 0 because the first position in a list is at the index 0:
var i = 0
- We will access the item in the list, print it, then increase the value of i by one:
print(cars[i++])
- We will loop as long as i is less than the list length:
i < cars.length
Let's see the code in DartPad: