Open In App

Dart – Loops

Improve
Improve
Like Article
Like
Save
Share
Report

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

  • for loop
  • for… in loop
  • for each 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; text expression){
    // Body of the loop
}

Control flow: 

Control flow goes as: 

  1. initialization
  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: 
 

Dart




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


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 execution flow is also the same as that in Java.
 

Syntax: 

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

Example: 
 

Dart




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


Output: 
 

1
2
3
4
5

for each … loop

The for-each loop iterates over all elements in some container/collectible and passes the elements to some specific function.

Syntax:

 collection.foreach(void f(value))

Parameters:

  • f( value): It is used to make a call to the f function for each element in the collection.

Dart




void main() {
  var GeeksForGeeks = [1,2,3,4,5];
  GeeksForGeeks.forEach((var num)=> print(num));
}


Output:

1
2
3
4
5

while loop

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

Syntax: 

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

Example: 
 

Dart




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


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: 
 

Dart




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


Output: 
 

Hello Geek
Hello Geek
Hello Geek
Hello Geek

 



Last Updated : 21 Sep, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads