Loops in Dart
By Syncfusion®, Inc. · Last updated
How to repeat work with for, while and do-while loops, how to stop or skip rounds, nested loops, and looping over a list.
What Is a Loop?
Loop = code that repeats a block again and again, while a condition is true.
For example:
- print the 7 times table, from
7 × 1to7 × 10 - add up the marks of every student
- keep asking for a password until it is right
Without a loop, you would copy the same line many times.
Simple lesson: a loop repeats work, so you write the code once and Dart runs it many times.
A Real-World Example
At morning assembly, the teacher calls roll numbers 1 to 40.
- She does not write 40 different instructions.
- She follows one rule: "start at 1, call the number, go to the next one, stop after 40".
- Start, check, do, next. That is exactly how a loop works.
Every Run box on this page runs on the course's Dart runner in your browser.
If a loop never ends, the runner stops it after a few seconds.
What You Will Learn
In this lesson, you will learn:
- What loops are and why we use them.
- The
forloop and its three parts. - The
whileanddo-whileloops. - How to avoid infinite loops, and how
breakandcontinuework. - Nested loops, and looping over a list with
for-inandforEach().
Loop Fundamentals
Why Loops Are Used
Compare these two programs. Both print the same thing.
Without a loop, and with a loop
void main() {
print('Good morning!');
print('Good morning!');
print('Good morning!');
print('---');
for (var i = 1; i <= 3; i++) {
print('Good morning!');
}
}
- Without a loop: to print it 100 times, you write 100 lines.
- With a loop: you change one number,
3to100.
Repetition and Loop Conditions
Iteration = one trip through the loop body. People also call it one round.
Loop condition = the question asked before each round, like i <= 3.
- While the condition is
true, the loop runs another round. - When it becomes
false, the loop stops.
Simple lesson: a loop keeps going while its condition is true, and stops when it turns false.
for Loop
for loop = a loop with a counter, best when you know how many rounds you need.
for (initialization; condition; update) {
// body
}
The Three Parts
- Initialization =
var i = 1. Runs once, at the start. - Condition =
i <= 10. Checked before every round. - Update expression =
i++. Runs after every round.
Change the end and step, then step through the rounds:
Look at the last chip: the loop stops when the condition becomes false.
The 7 times table
void main() {
for (var i = 1; i <= 10; i++) {
print('7 x $i = ${7 * i}');
}
}
Adding Up in a Loop
A loop often builds a total step by step:
Add the numbers from 1 to 100
void main() {
var total = 0;
for (var n = 1; n <= 100; n++) {
total += n;
}
print('Total: $total');
}
totalstarts at0, before the loop.- Each round adds the next number.
- After 100 rounds,
totalis5050.
Simple lesson: a for loop has a start, a condition and an update, all on one line.
while Loop
while loop = repeats while a condition is true. Best when you do not know how many rounds you need.
while (condition) {
// body
}
Entry-controlled loop = the condition is checked before each round. If it is false at the start, the body never runs.
A countdown with while
Common Use Cases
- Keep going until a goal is reached, like saving ₹500.
- Keep reading input until the user types something valid.
- Repeat until a game is over.
How many weeks to save ₹500?
void main() {
var savings = 0;
var weeks = 0;
while (savings < 500) {
savings += 120;
weeks++;
}
print('After $weeks weeks you have ₹$savings.');
}
Simple lesson: use while when you know the stopping rule, but not the number of rounds.
do-while Loop
do-while loop = runs the body first, then checks the condition.
Exit-controlled loop = the condition is checked after each round. The body always runs at least once.
do {
// body
} while (condition);
Note the ; after the condition.
Add numbers until the user types 0
import 'dart:io';
void main() {
var total = 0;
var number = 0;
do {
print('Enter a number (0 to stop):');
number = int.tryParse(stdin.readLineSync() ?? '') ?? 0;
total += number;
} while (number != 0);
print('Total: $total');
}
Common Use Cases
- Menus: show the menu at least once, then repeat until the user chooses "Exit".
- Input: ask once, then ask again only if the answer was wrong.
while or do-while?
Simple lesson: do-while always runs once, then repeats while the condition is true.
Infinite Loops
Infinite loop = a loop whose condition never becomes false, so it never ends.
var count = 1;
while (count <= 5) {
print(count);
}
count never changes, so count <= 5 is always true. The program hangs.
Causes of Infinite Loops
- Forgetting the update: no
count++inside the loop. - Updating the wrong way:
i--when the loop needsi++. - A condition that can never be false:
while (true)with no way out.
Avoiding Infinite Loops
- Check that something in the condition changes every round.
- Check that it changes towards the stopping point.
- Give
while (true)abreak(see the next section).
Here is the fixed version:
The fixed loop
void main() {
var count = 1;
while (count <= 5) {
print(count);
count++;
}
}
On your computer, an infinite loop runs until you stop it. Press Ctrl + C in the terminal.
In this course's runner, it is stopped after a few seconds.
Simple lesson: every loop needs something that moves it towards its stopping point.
Loop Control Statements
break
break = leave the loop immediately, even if the condition is still true.
Stop at the first failing mark
void main() {
var marks = [78, 92, 30, 85, 66];
for (var m in marks) {
if (m < 35) {
print('Found a failing mark: $m');
break;
}
print('Checked $m');
}
}
85 and 66 are never checked. break ended the loop.
continue
continue = skip the rest of this round, and go to the next round.
Skip the absent students
void main() {
for (var roll = 1; roll <= 6; roll++) {
if (roll == 2 || roll == 5) {
continue;
}
print('Roll $roll: present');
}
}
break= stop the whole loop.continue= skip just one round.
Simple lesson: break leaves the loop, and continue jumps to the next round.
Nested Loops
Nested loop = a loop inside another loop.
- The inner loop runs completely for every round of the outer loop.
- 3 outer rounds × 4 inner rounds = 12 inner rounds in total.
A small times-table grid
import 'dart:io';
void main() {
for (var row = 1; row <= 3; row++) {
for (var col = 1; col <= 4; col++) {
stdout.write('${row * col}\t');
}
print('');
}
}
stdout.write prints without moving to a new line. It needs import 'dart:io';, like stdin. print('') ends each row.
Practical Examples
A star staircase
void main() {
for (var line = 1; line <= 4; line++) {
var stars = '';
for (var s = 1; s <= line; s++) {
stars += '* ';
}
print(stars);
}
}
Nested loops are used for grids, seating charts, timetables and games like tic-tac-toe.
Simple lesson: the inner loop finishes all its rounds before the outer loop takes one step.
Collection Iteration
Iterate = go through the items of a collection one by one.
A list holds many values in order, like ['Asha', 'Ravi', 'Priya']. You will learn lists fully in Lists.
for-in
for-in = "for each item in this list, run the body".
Greet every student
void main() {
var students = ['Asha', 'Ravi', 'Priya'];
for (var name in students) {
print('Good morning, $name!');
}
}
No counter, and no index. Dart hands you each item in turn.
forEach()
forEach() = a method that runs a function for every item.
forEach with a short function
void main() {
var marks = [78, 92, 65];
marks.forEach((m) => print('Mark: $m'));
}
(m) => print(...) is a small function. You will learn this form in Functions.
Easy way to remember
- Know the count:
for. - Know the stopping rule:
while. - Must run at least once:
do-while. - Have a list:
for-in.
Simple lesson: use for-in to visit every item in a list, without counting.
TL;DR
- Loop = repeats a block while a condition is
true. One trip = one iteration. for (init; condition; update)= best when you know the count.while= checks first, may run zero times.do-while= runs first, always at least once.
Infinite loop = the condition never becomes false. Always change something.
break= leave the loop.continue= skip to the next round.
Nested loop = a loop inside a loop.
for-inandforEach()= visit every item in a list.
Common mistakes
| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
No update in a while loop | The loop moves on by itself | Change the variable inside the loop | An infinite loop. |
i <= 10 when you meant 10 rounds from 0 | The end number is excluded | 0 to 10 with <= is 11 rounds | One round too many. |
total = 0 inside the loop | The start value can go anywhere | Set it before the loop | The total resets every round. |
; after for (...) | It is harmless | for (...); has an empty body | The body runs only once, after the loop. |
Missing ; after do-while | while (x) ends it | Write } while (x); | Expected ';' after this. |
break to skip one item | break skips | continue skips, break stops | The loop stops too early. |
Changing a list inside its for-in | It updates the loop | Do not add or remove items while looping | A ConcurrentModificationError. |
Check Yourself
Exercises
What to Remember
- A loop repeats a block while its condition is
true. foris for a known count.whilechecks first.do-whilealways runs once.- Every loop needs something that changes, or it never ends.
breakleaves the loop, andcontinueskips to the next round.for-inandforEach()visit every item in a list.
Next: Functions. You will learn to name a block of code and reuse it, with inputs and outputs.