for, while & do-while Loops
for, while & do-while Loops
Loops let you repeat a block of code multiple times without rewriting it. Whether you're printing a table, summing numbers, or processing a list, loops are the backbone of repetitive computation. Dart gives you three fundamental loop types: for, while, and do-while.
🔹 The for Loop
The classic for loop is perfect when you know exactly how many times you want to repeat.
Syntax:
dartfor (initialization; condition; increment) { // body }
dartvoid main() { for (int i = 1; i <= 5; i++) { print('Count: $i'); } }
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
How It Works — Step by Step
| Step | What Happens |
|---|---|
| 1. Initialization | int i = 1 — runs once before the loop starts |
| 2. Condition check | i <= 5 — checked before each iteration |
| 3. Body | Code inside {} runs if condition is true |
| 4. Increment | i++ — runs after each iteration |
| 5. Repeat from 2 | Until condition is false |
Counting Down
dartvoid main() { for (int i = 10; i >= 1; i--) { print(i); } print('Blast off!'); }
Stepping by More Than One
dartvoid main() { // Even numbers from 0 to 20 for (int i = 0; i <= 20; i += 2) { print(i); } }
Loop Variable Scope
The variable declared in the for initialization (int i) is scoped to the loop and cannot be used after it:
dartvoid main() { for (int i = 0; i < 3; i++) { print(i); // i is accessible here } // print(i); // ERROR! i is not defined here }
🔹 Nested for Loops
A loop inside another loop — the inner loop completes fully for each iteration of the outer loop:
dartvoid main() { for (int i = 1; i <= 3; i++) { for (int j = 1; j <= 3; j++) { print('($i, $j)'); } } }
Output:
(1, 1)
(1, 2)
(1, 3)
(2, 1)
(2, 2)
(2, 3)
(3, 1)
(3, 2)
(3, 3)
Multiplication Table (Nested Loop Example)
dartvoid main() { int n = 5; // table size for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { // padLeft(4) for alignment String cell = (i * j).toString().padLeft(4); stdout.write(cell); } print(''); // newline after each row } }
Output:
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
Tip: Import dart:io to use stdout.write() which prints without a newline. Alternatively, build a string and print once.
🔹 The while Loop
The while loop repeats as long as a condition is true. Use it when you don't know in advance how many times you'll need to loop.
Syntax:
dartwhile (condition) { // body }
The condition is checked before each iteration. If it's false from the start, the body never runs.
dartvoid main() { int count = 1; while (count <= 5) { print('Count: $count'); count++; } }
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
When to Use while
while is most natural when the stopping condition depends on something that changes unpredictably:
dartvoid main() { int number = 1; // Double until we exceed 100 while (number <= 100) { number *= 2; } print(number); // 128 (first power of 2 that exceeds 100) }
The Infinite Loop Risk
If the condition never becomes false, the loop runs forever — this is a bug! Always ensure the loop body moves toward the exit condition:
dartvoid main() { int i = 1; while (i <= 5) { print(i); i++; // Without this line, the loop runs forever! } }
Warning: An infinite loop (while (true) { ... }) will freeze your program unless you have an explicit break inside the body to exit.
🔹 The do-while Loop
The do-while loop is like while, but the condition is checked after the body runs. This guarantees the body runs at least once.
Syntax:
dartdo { // body (always runs at least once) } while (condition);
dartvoid main() { int count = 1; do { print('Count: $count'); count++; } while (count <= 5); }
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
When do-while Is Different from while
dartvoid main() { int x = 10; // while — body does NOT run (10 is not <= 5) while (x <= 5) { print('while: $x'); } // do-while — body runs ONCE even though 10 is not <= 5 do { print('do-while: $x'); } while (x <= 5); }
Output:
do-while: 10
Perfect Use Case: Input Validation (conceptual)
dart// Conceptual example — in a real app, input comes from a form or stdin void main() { int attempts = 0; String password = ''; // Always ask at least once do { attempts++; // Simulating: in a real app, you'd read from user input here password = attempts == 3 ? 'correct' : 'wrong'; // Simulate 3rd attempt succeeds print('Attempt $attempts: "$password"'); } while (password != 'correct'); print('Access granted after $attempts attempt(s).'); }
🔹 Performance Considerations
- All three loops have O(n) complexity for a single loop — performance is comparable for simple use cases.
- Nested loops are O(n²) or worse — be careful with large datasets.
- For iterating over collections, prefer
for-in(covered in the next lesson) which is cleaner and often slightly more efficient. - Avoid doing heavy computation inside the condition of a
whileloop — compute it before if possible.
🔹 Real-World Examples
Example 1: Sum of a List
dartvoid main() { List<int> numbers = [10, 25, 3, 47, 8, 16]; int sum = 0; for (int i = 0; i < numbers.length; i++) { sum += numbers[i]; } print('Sum: $sum'); // Sum: 109 }
Example 2: Fibonacci Sequence
dartvoid main() { int n = 10; // Print first 10 Fibonacci numbers int a = 0, b = 1; print('Fibonacci sequence:'); for (int i = 0; i < n; i++) { stdout.write('$a '); int temp = a + b; a = b; b = temp; } print(''); }
Output: 0 1 1 2 3 5 8 13 21 34
Example 3: Palindrome Check
dartbool isPalindrome(String word) { word = word.toLowerCase(); int left = 0; int right = word.length - 1; while (left < right) { if (word[left] != word[right]) { return false; } left++; right--; } return true; } void main() { List<String> words = ['radar', 'hello', 'level', 'dart', 'racecar']; for (String word in words) { String result = isPalindrome(word) ? 'is a palindrome' : 'is NOT a palindrome'; print('"$word" $result'); } }
Output:
"radar" is a palindrome
"hello" is NOT a palindrome
"level" is a palindrome
"dart" is NOT a palindrome
"racecar" is a palindrome
Example 4: Star Pattern (Nested Loop)
dartvoid main() { int rows = 5; for (int i = 1; i <= rows; i++) { String row = ''; for (int j = 1; j <= i; j++) { row += '* '; } print(row); } }
Output:
*
* *
* * *
* * * *
* * * * *
Summary
| Loop | Condition Checked | Minimum Runs | Best Used When |
|---|---|---|---|
for | Before each iteration | 0 (if condition false initially) | Known number of iterations |
while | Before each iteration | 0 (if condition false initially) | Condition-driven, unknown iterations |
do-while | After each iteration | Always at least 1 | Must execute at least once |
Loops are fundamental to programming. Once you understand these three, you'll also want to know about for-in, break, and continue — which we cover in the very next lesson!