Dart While Loop Tutorial With Examples

0
7383
while loop in dart tutorial
Dart while loop with examples

Dart while loop executes its code block as long as the condition is true. The functionality of while loop is very similar to for loop but in while loop first the condition is verified then while loop code block is executed and later on incremental/ decremental variable value is changed to control the flow of while loop.

The syntax of while loop in dart looks like this.

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

Dart While Loop Examples

In this tutorial, We will cover the same examples that we did in our conventional for loop code. First of all, let’s print the numbers from 1 to 10 using a while loop.

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

The result is

  
1
2
3
4
5
6
7
8
9
10

Pretty easy! In the next example let’s print the even numbers from 1 to 10 using a while loop code.

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

Nothing new just a condition if the number is divisible by 2 or not. Output is

  
2
4
6
8
10

In out first example we have printed number from 1 to 10. This time print the numbers from 10 to 1 using a simple while loop. Here is the code.

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

After hitting the run button.

  
10
9
8
7
6
5
4
3
2
1

This is all from our while loop tutorial. I hope now while loop is pretty much clear.

LEAVE A REPLY

Please enter your comment!
Please enter your name here