For Loops
Loops are used to execute a set of statements repeatedly until a particular condition is satisfied.
It can be used to iterate over a fixed set of values, such as a list.
- Syntax:
- Flow of Execution:
- Examples:
- For..in Loop
for ( initialization; condition; increment/decrement ) {
statement(s);
}
First step: In for loop, initialization happens first and only one time, which means that the initialization part of for loop only executes once.
Second step: Condition in for loop is evaluated on each iteration, if the condition is true then the statements inside for loop body gets executed. Once the condition returns false, the statements in for loop does not execute and the control gets transferred to the next statement in the program after for loop.
Third step: After every execution of for loop’s body, the increment/decrement part of for loop executes that updates the loop counter.
Fourth step: After third step, the control jumps to second step and condition is re-evaluated.
void main() {
for (int i = 8; i > 0; i--) {
print("i = $i");
}
for (int j = 1; j < 9; j++) {
print("j = $j");
}
}
i = 7
i = 6
i = 5
i = 4
i = 3
i = 2
i = 1
j = 1
j = 2
j = 3
j = 4
j = 5
j = 6
j = 7
j = 8
void main() {
for (int i = 8, j = 1; i > 0 && j < 9; i--, j++) {
print("i = $i and j = $j");
}
}
i = 7 and j = 2
i = 6 and j = 3
i = 5 and j = 4
i = 4 and j = 5
i = 3 and j = 6
i = 2 and j = 7
i = 1 and j = 8
For..in loop is useful when you want to iterate classes such as List and Set , it is easy to write and understand.
void main() {
var list1 = [1, 2, 3];
for (var x in list1) {
print(x);
}
print("////////");
var set1 = {"one", "two", "three"};
for (var x in set1) print(x);
}
2
3
////////
one
two
three