Back to quest
Control Flow & FunctionsLevel 17 / 32

Loops

For, While, and Do-While loops

Loops allow you to run the same block of code multiple times. This is useful for processing lists of items or repeating tasks until a condition is met.

1. For & For-In Loops

Control exactly how many times code runs, or iterate over collections easier.

For Loop Variations

example.dart
1// Standard Counter
2for (int i = 0; i < 5; i++) {
3 print('Step $i');
4}
5 
6// For-In (Best for Lists)
7List<String> colors = ['Red', 'Green', 'Blue'];
8for (var color in colors) {
9 print(color);
10}
11 
12// forEach Method (Functional style)
13colors.forEach((c) => print(c));

HintUse standard for when you need the index i. Use for-in when you just need the values.

2. While vs Do-While

The difference is when they check the condition: Before running (While) or After running (Do-While).

Check First vs Check Last

example.dart
1int count = 0;
2 
3// While: Might never run
4while (count > 10) {
5 print('This will NOT print');
6}
7 
8// Do-While: Runs at least once
9do {
10 print('This PRINTS once');
11} while (count > 10);

Hintdo-while is perfect for scenarios like "Show menu, then check if user wants to exit".

3. Controlling Loops (Break & Continue)

You can alter the flow of a loop using break (stop immediately) or continue (skip to next round).

Break and Continue

example.dart
1for (int i = 1; i <= 5; i++) {
2 if (i == 2) {
3 continue; // Skip 2
4 }
5 if (i == 4) {
6 break; // Stop completely at 4
7 }
8 print(i);
9}
10// Output:
11// 1
12// 3

Hintcontinue jumps back to the top of the loop. break jumps completely out of the loop block.

Loot collected

Key takeaways
  • Use for loops when you know how many times to iterate.
  • Use for-in to easily loop through Lists and Sets.
  • Use while loops when looping depends on a condition, not a count.
  • Always ensure your loop has a way to stop (exit condition).

Side quests

Practice exercises

1

Exercise 1: Basic Counter

Write a loop that prints numbers from 1 to 10.

Reveal solution
solution.dart
1for (int i = 1; i <= 10; i++) print(i);
2

Exercise 2: List Iteration

Given var nums = [10, 20, 30], print each number multiplied by 2.

Reveal solution
solution.dart
1for (var n in nums) print(n * 2);
Party chat

Comments