Dart Do While Loop Tutorial With Examples

1
1801
do while loop in dart tutorial
Dart do while loop example

Dart do while loop is another form of simple while loop but in do while loop the code block is executed once before the condition is checked. Do while loop execute the code as long as the condition is true.

One more difference from while loop is do while loop will execute the code once even the condition is not true.

The syntax of do while loop looks like this.

  
do {
  // code block to be executed
}
while (condition);

Dart do while loop examples

Now the do while loop syntax is known. It is time to run some examples code. Let’s print the numbers from 1 to 10 using do while loop.

  
void main() {
  var i = 1;
  do {
    print(i);
    i++;
  } while (i <= 10);
}

The result of this code is

  
1
2
3
4
5
6
7
8
9
10

This time find the even numbers from 1 to 10 using do while loop in Dart.

  
void main() {
  var i = 1;
  do {
    if (i % 2 == 0) print(i);
    i++;
  } while (i <= 10);
}

We just have added one condition if the number is completely divisible by 2 or not. The result of this code is given below

  
2
4
6
8
10

As we have printed numbers from 1 to 10 using do while loop. Now print these numbers in reverse order using the same do while loop. Code is

  
void main() {
  var i = 10;
  do {
    print(i);
    i--;
  } while (i >= 1);
}

The expected outcome is

  
10
9
8
7
6
5
4
3
2
1

do while loop is pretty simple and we have done a few examples as well.

1 COMMENT

  1. What condition I need to use if I want the do while loop to exit for numbers 1,2 and 3 and keep looping for all other numbers?

LEAVE A REPLY

Please enter your comment!
Please enter your name here