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
1// Standard Counter2for (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
1int count = 0;2 3// While: Might never run4while (count > 10) {5 print('This will NOT print');6}7 8// Do-While: Runs at least once9do {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
1for (int i = 1; i <= 5; i++) {2 if (i == 2) {3 continue; // Skip 24 }5 if (i == 4) {6 break; // Stop completely at 47 }8 print(i);9}10// Output:11// 112// 3Hintcontinue jumps back to the top of the loop. break jumps completely out of the loop block.
Loot collected
Key takeaways- Use
forloops when you know how many times to iterate. - Use
for-into easily loop through Lists and Sets. - Use
whileloops when looping depends on a condition, not a count. - Always ensure your loop has a way to stop (exit condition).
Side quests
Practice exercises
Exercise 1: Basic Counter
Write a loop that prints numbers from 1 to 10.
Reveal solutionHide solution
1for (int i = 1; i <= 10; i++) print(i);Exercise 2: List Iteration
Given var nums = [10, 20, 30], print each number multiplied by 2.
Reveal solutionHide solution
1for (var n in nums) print(n * 2);