In this chapter, we will learn about the dart for…in loop with the help of examples.
The for loop is used to iterate with a particular condition. The dart for..in loop is useful when we need loop over the Dart objects such as list, map, and set.
for…in Loop
The dart for…in loop iterates over the element of an object one at a time.
The syntax for for…in loop is:
for(variable in Object) {
// statements
}
The variable represents the variable name that accesses each element of the list one at a time.
Object contains the collection of ordered groups of elements.
Access Each element from a List
void main() {
var numbers = [1, 2, 3, 4, 5];
for (var num in numbers) {
print(num);
}
}
Output
1
2
3
4
5
Here, the numbers list consist of a group of numbers.
The num variable gets access to each element one at a time.
- During the first iteration, the num variable gets 1 and prints it.
- During the second iteration, the num variable gets 2 and prints it.
This continues for all the elements available. And the loop terminates when there are no more elements to access.
Performing Operations on Elements
Once each element is accessed using the dart for…in statement, we can perform various operations using those elements. For example,
void main() {
var numbers = [1, 2, 3, 4, 5];
int sum = 0;
for (var num in numbers) {
sum += num; // sum = sum + num;
}
print('Final sum is: $sum');
}
Output
Final sum is: 15
In this program, num variable access each element and adds to the previous sum.
First, the value of sum is 0.
- On the first iteration, the sum variable adds 1 to it. The sum is now 1.
- On the second iteration, the sum variable adds 2 to it. The sum has now value 3.
- During the third iteration, the sum variable adds 3 to it. And the sum has now value 6.
- During the fourth iteration, the sum variable adds 4 to it. The sum has now value 10.
- During the fifth iteration, the sum variable adds 5 to it. The sum has now value 15. And since all the elements have been accessed, the loop terminates. Hence the final sum is 15.
To see the flow of the program, we can print the num variable and the sum variable inside each iteration. For example,
void main() {
var numbers = [1, 2, 3, 4, 5];
int sum = 0;
for (var num in numbers) {
sum += num;
print('num value: $num');
print('sum value: $sum');
}
print('Final sum is: $sum');
}
Output
num value: 1
sum value: 1
num value: 2
sum value: 3
num value: 3
sum value: 6
num value: 4
sum value: 10
num value: 5
sum value: 15
Final sum is: 15