Dart for..in Loop

Dart for..in Loop

The for..in loop is similar to for loop but different in its syntax. It iterates through an object's properties. The Dart for..in loop accepts an expression as iterator and iterates through the elements one at a time in sequence. The variable var holds the values of the iteration. The for…in will execute until elements remain in iterators.

Dart For In Loop Flow Diagram

Dart for..in Loop

The syntax is given below.

Syntax:

  1. for (var in expression) {  
  2.      //statement(s)  
  3. }  

Let's understand the following example.

Example -

  1. void main() {  
  2.    var list1 = [10,20,30,40,50];  
  3.    print("Dart for..in loop Example");  
  4.      
  5.    for(var i in list1) {  
  6.           print(i);           
  7. }  
  8. }  

Output:

Dart for..in loop Example
10
20
30
40
50

Explanation:

In the above program, we have iterator list1 and variable i. In the first iteration of the loop, the first element of the list assigned to the variable i. This process happened again, and the second element of the list assigned to i. It will be continued until there is no element left in the list. It printed the all element of the list to the console.

The for..in loop is suitable to iterate over the Dart object such as list, map, and set, where for loop is more effective to iterate along with the specified condition.

Let's understand another example.

Example -

  1. void main() {  
  2.    var list1 = [10,20,30,40,50];  
  3.    // create an integer variable   
  4.    int sum = 0;  
  5.    print("Dart for..in loop Example");  
  6.      
  7.    for(var i in list1) {   
  8.     // Each element of iterator and added to sum variable.  
  9.           sum = i+ sum;           
  10. }  
  11. print("The sum is : ${sum}");  
  12. }  

Output:

Dart for..in loop Example
The sum is : 150

Explanation:

In the above example, we have declared a variable sum with value 0. We have a for..in loop with the iterator list, and each element of list added to the sum variable after each iteration.

In the first iteration, the value of the sum is equal to 10. In the next iteration, the value of sum became 30 after added 20 to it. After complete the iteration, it returned the sum of all elements of the list

Comments