Dart Loops
There are three kinds of looping statements in Dart. They are
- While Loop
- Do-while Loop
- For Loop
Also, there are some statements that can control the execution of these loop statements. They are called loop-control statements. They are
- break
- continue
While Loop
Refer Dart While Loop tutorial, where a detailed syntax and examples are provided.
The following is a simple example of while loop statement in Dart.
main.dart
void main() { var i = 0; while (i < 5) { print('Hello World'); i++; } }
Output
Hello World Hello World Hello World Hello World Hello World
Do-While Loop
Refer Dart Do-While Loop tutorial, where a detailed syntax and examples are provided.
The following is a simple example of do-while loop statement in Dart.
main.dart
void main() { var i = 0; do { print('Hello World'); i++; } while (i < 5); }
Output
Hello World Hello World Hello World Hello World Hello World
For Loop
Refer Dart For Loop tutorial, where a detailed syntax and examples are provided.
The following is a simple example of For loop statement in Dart that find the factorial of n
.
Dart program
void main(){ var n = 6; var factorial = 1; //for loop to calculate factorial for(var i=2; i<=n; i++) { factorial = factorial*i; } print('Factorial of ${n} is ${factorial}'); }
Output
Factorial of 6 is 720
Continue Statement
In this example, we print numbers from 1 to 7 using while loop. But when i=5
, we skip the iteration, continue with the next iteration.
Refer Dart Continue tutorial for more examples of using continue statement.
main.dart
void main() { var i = 0; while (i < 7) { i++; if (i == 5) { continue; } print(i); } }
Output
1 2 3 4 6 7
Break Statement
In this example, we print numbers from 1 to 7 using while loop. But when i=5
, we break the loop using break statement.
Refer Dart Break tutorial for more examples of using break statement.
main.dart
void main() { var i = 0; while (i < 7) { i++; if (i == 5) { break; } print(i); } }
Output
1 2 3 4
Conclusion
In this Dart Tutorial, we have learnt about different loop statements, and loop control statements in Dart language, with examples.