A loop runs a piece of code over and over. It's essential for displaying data from a List, calculating totals, and doing search/filter operations.
dart
void main() {
List<int> prices = [3000, 5000, 7000];
int total = 0;
for (final price in prices) {
total += price;
}
print('Total: $total');
int count = 1;
while (count <= 3) {
print('Attempt $count');
count++;
}
}for-in loop grabs each price in the List and adds it into total. while loop keeps running as long as the condition holds, and count++ bumps count up by 1.
You should see
Total: 15000 Attempt 1 Attempt 2 Attempt 3