Loops in Dart
Lesson#9
Loops are used in any programming language to execute block of statements number of time. In Dart there are two loop structures/statements i.e. for and while.
for Loop
Syntax of the for loop is:
for (initialization statement ; condition ; increment statement)
body;
At the start the initialization statement is executed, then the condition is evaluated, if condition is true then body is executed, after execution of the body the increment statement is executed, after increment statement condition is evaluated and loop goes on until condition becomes false.
Example: Loop that prints numbers from 0 to 4.
void main() {
int x;
for(x = 0; x < 5 ; x++)
print(x);
}
/* prints
0
1
2
3
4
*/
for-in loop
Another variation of for loop is for-in, in which the loop is iterated within a list.
Example:
void main() {
var students = ["Ali", "Muhammad", "Umer", "Salman"];
for (var student in students) {
print(student);
}
}
/*
Ali
Muhammad
Umer
Salman
*/
while loop
The 2nd control structure/statement in Dart is while loop.
Syntax of the while loop is:
while(condition) {
body;
}
Example: Loop that prints numbers from 0 to 4.
void main() {
int x=0;
while (x<5) {
print(x);
x++;
}
}
/* prints
0
1
2
3
4
*/