Lesson 18 min

for, while & do-while Loops

00:00 / 00:00

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:

dart
for (initialization; condition; increment) { // body }
dart
void 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

StepWhat Happens
1. Initializationint i = 1 — runs once before the loop starts
2. Condition checki <= 5 — checked before each iteration
3. BodyCode inside {} runs if condition is true
4. Incrementi++ — runs after each iteration
5. Repeat from 2Until condition is false

Counting Down

dart
void main() { for (int i = 10; i >= 1; i--) { print(i); } print('Blast off!'); }

Stepping by More Than One

dart
void 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:

dart
void 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:

dart
void 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)

dart
void 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:

dart
while (condition) { // body }

The condition is checked before each iteration. If it's false from the start, the body never runs.

dart
void 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:

dart
void 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:

dart
void 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:

dart
do { // body (always runs at least once) } while (condition);
dart
void 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

dart
void 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 while loop — compute it before if possible.

🔹 Real-World Examples

Example 1: Sum of a List

dart
void 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

dart
void 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

dart
bool 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)

dart
void 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

LoopCondition CheckedMinimum RunsBest Used When
forBefore each iteration0 (if condition false initially)Known number of iterations
whileBefore each iteration0 (if condition false initially)Condition-driven, unknown iterations
do-whileAfter each iterationAlways at least 1Must 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!

WhatsApp