Dart: Loops

# for Loop

for (initial_count_value; termination-condition; step) { 
   //statements 
} 

Example

void main() { 
   for(var temp, i = 0, j = 1; j<30; temp = i, i = j, j = i + temp) { 
      print('${j}'); 
   } 
} 

=> output

1 
1 
2 
3 
5
8 
13 
21

# for-in Loop

for (variablename in object){  
   statement or block to execute  
}

Example

void main() { 
   var obj = [1,2,3]; 
   
   for (var prop in obj) { 
      print(prop); 
   } 
} 

=> output

1
2
3

# while Loop

while (expression) {
   Statement(s) to be executed if expression is true  
}

Example

void main() { 
   var num = 4; 
   var factorial = 1; 
   
   while(num >=1) { 
      factorial = factorial * num; 
      num--; 
   } 
   print("The factorial  is ${factorial}"); 
}  
The factorial is 24

Leave a Reply

Your email address will not be published. Required fields are marked *