Dart – Loops

Looping statement in Dart or any other programming language is used to repeat a certain set of commands until certain conditions are not completed. There are different ways to do so. They are:

  • for loop
  • for… in loop
  • while loop
  • do while loop

for loop:

For loop in Dart is similar to that in Java and also the flow of execution is the same as that in Java.

Syntax:

for(initialization; condition; test expression){
    // Body of the loop
}

Control flow:
Control flow goes as:

  1. initialzation
  2. condition
  3. body of loop
  4. test expression

The first is executed only once i.e in the beginning while the other three are executed until the condition turns out to be false.



Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

// Printing GeeksForGeeks 5 times
void main()
{
    for (int i = 0; i < 5; i++) {
        print('GeeksForGeeks');
    }
}

chevron_right


Output:

GeeksForGeeks
GeeksForGeeks
GeeksForGeeks
GeeksForGeeks
GeeksForGeeks

for…in loop:

For…in loop in Dart takes an expression or object as an iterator. It is similar to that in Java and its flow of execution is also the same as that in Java.

Syntax:

for (var in expression) {
   // Body of loop
}

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

void main()
{
    var GeeksForGeeks = [ 1, 2, 3, 4, 5 ];
    for (int i in GeeksForGeeks) {
        print(i);
    }
}

chevron_right


Output:

1
2
3
4
5

while loop:

The body of loop will run until and unless condition is true.

Syntax:

while(condition){
    text expression;
    // Body of loop
}

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

void main()
{
    var GeeksForGeeks = 4;
    int i = 1;
    while (i <= GeeksForGeeks) {
        print('Hello Geek');
        i++;
    }
}

chevron_right


Output:

Hello Geek
Hello Geek
Hello Geek
Hello Geek

do..while loop:

The body of the loop will be executed first and then the condition is tested.

Syntax:

do{
    text expression;
    // Body of loop
}while(condition);

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

void main()
{
    var GeeksForGeeks = 4;
    int i = 1;
    do {
        print('Hello Geek');
        i++;
    } while (i <= GeeksForGeeks);
}

chevron_right


Output:

Hello Geek
Hello Geek
Hello Geek
Hello Geek



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.