6 Loops¶
In the first five chapters of this book, your code ran from the top of the main
function to the bottom, and then it was finished. With the addition of if
statements in the previous chapter, you gave your code the opportunity to make decisions. However, it’s still running from top to bottom, albeit following different branches.
Rather than just running through a set of instructions once, it’s often useful to repeat tasks. Think about all the repetitious things you do every day:
- Breathing: Breathe in, breathe out, breathe in, breathe out…
- Walking: Right leg forward, left leg forward, right leg forward, left leg forward…
- Eating: Spoon up, spoon down, chew, chew, chew, swallow, repeat…
Computer programming is just as full of repetitive actions as your life is. The way you can perform these actions is by using loops. Dart, like many programming languages, has while
loops and for
loops. You’ll learn how to make them in the following sections.
While Loops¶
A while loop repeats a block of code as long as a Boolean condition is true. You create a while loop like so:
while (condition) {
// loop code
}
The loop checks the condition on every iteration. If the condition is true
, then the loop executes and moves on to another iteration. If the condition is false
, then the loop stops. Just like if
statements, while
loops introduce a scope because of their curly braces.
The simplest while
loop takes this form:
while (true) { }
This is a while
loop that never ends because the condition is always true
. Of course, you would never write such a while
loop, because your program would spin forever! This situation is known as an infinite loop, and while it might not cause your program to crash, it will very likely cause your computer to freeze.
If you actually tried to run that infinite loop in VS Code and can’t figure out how to make it stop, press the Stop button:
Here’s a somewhat more useful example of a while
loop:
var sum = 1;
while (sum < 10) {
sum += 4;
print(sum);
}
Run that to see the result. The loop executes as follows:
- Before 1st iteration: sum =
1
, loop condition =true
- After 1st iteration: sum =
5
, loop condition =true
- After 2nd iteration: sum =
9
, loop condition =true
- After 3rd iteration: sum =
13
, loop condition =false
After the third iteration, the sum
variable is 13
, and therefore the loop condition of sum < 10
becomes false
. At this point, the loop stops.
Do-While Loops¶
A variant of the while
loop is called the do-while
loop. It differs from the while
loop in that the condition is evaluated at the end of the loop rather than at the beginning. Thus, the body of a do-while
loop is always executed at least once.
You construct a do-while
loop like this:
do {
// loop code
} while (condition)
Whatever statements appear inside the braces will be executed. Finally, if the while
condition after the closing brace is true
, you jump back up to the beginning and repeat the loop.
Here’s the example from the last section, but using a do-while
loop:
var sum = 1;
do {
sum += 4;
print(sum);
} while (sum < 10);
In this example, the outcome is the same as before.
Comparing While and Do-While Loops¶
It’s possible to only use while
loops, but in some cases, your code will be cleaner with a do-while
loop. Take the following while
loop as an example:
var sum = (1 + 3 - 2 * 4 + 8);
while (sum < 10) {
sum += (1 + 3 - 2 * 4 + 8);
}
print('while loop sum: $sum');
All that math in the parentheses is there merely to represent a complex operation that you need to run at least once, and then run again on every iteration of the loop.
Note
In Chapter 7, “Functions”, you’ll learn about grouping related code into a single complex operation called a function. Since you haven’t studied functions yet, though, this chapter represents the idea by using a series of mathematical operations.
The problem with the while
loop above is that you need to repeat (1 + 3 - 2 * 4 + 8)
both to initialize the variable and on every iteration of the loop. Using a do-while
loop eliminates the need for repetition:
var sum = 0;
do {
sum += (1 + 3 - 2 * 4 + 8);
} while (sum < 10);
print('do-while loop sum: $sum');
Here, you only wrote the complex operation code once. Less repetition makes for cleaner code!
Breaking Out of a Loop¶
Sometimes you’ll need to break out of a loop early. You can do this using the break
statement, just as you did from inside the switch
statement earlier. This immediately stops the execution of the loop and continues on to the code that follows the loop.
For example, consider the following while
loop:
sum = 1;
while (true) {
sum += 4;
if (sum > 10) {
break;
}
}
Here, the loop condition is true
, so the loop would normally iterate forever. However, the break
means the while
loop will exit once the sum is greater than 10
.
You’ve now seen how to write the same loop in different ways. This demonstrates that in computer programming there are often many ways to achieve the same result. You should choose the method that’s easiest to read and that conveys your intent in the best way possible. This is an approach you’ll internalize with enough time and practice.
Exercise¶
- Create a variable named
counter
and set it equal to0
. - Create a
while
loop with the conditioncounter < 10
. - The loop body should print out “counter is X” (where X is replaced with the value of
counter
) and then incrementcounter
by 1.
For Loops¶
In addition to while
loops, Dart has another type of loop called a for loop. This is probably the most common loop you’ll see, and you use it to run a block of code a set number of times.
Here’s a simple example of a C-style for
loop in Dart:
for (var i = 0; i < 5; i++) {
print(i);
}
If you have some prior programming experience, this C programming language style for
loop probably looks very familiar to you. If not, though, the first line would be confusing. Here’s a summary of the three parts between the parentheses and separated by semicolons:
var i = 0
(initialization): Before the loop starts, you create a counter variable to keep track of how many times you’ve looped. You could call the variable anything, buti
is commonly used as an abbreviation for index. You then initialize it with some value; in this case,0
.i < 5
(condition): This is the condition that thefor
loop will check before every iteration of the loop. If it’strue
, then it will run the code inside the braces. But if it’sfalse
, then the loop will end.i++
(action): The action runs at the end of every iteration, usually to update the loop index value. It’s common to increment by1
usingi++
but you could just as easily usei += 2
to increment by2
ori--
to decrement by1
.
Run the previous code and you’ll see the following output:
0
1
2
3
4
The counter index i
started at 0
and continued until it equaled 5
. At that point, the for
loop condition i < 5
was false
, so the loop exited before running the print
statement again.
The Continue Keyword¶
Sometimes you want to skip an iteration only for a certain condition. You can do that using the continue
keyword. Have a look at the following example:
for (var i = 0; i < 5; i++) {
if (i == 2) {
continue;
}
print(i);
}
This example is similar to the last one, but this time, when i
is 2
, the continue
keyword will tell the for
loop to immediately go on to the next iteration. The rest of the code in the block won’t run on this iteration.
This is what you’ll see:
0
1
3
4
No 2
here!
More For Loops¶
There are two more kinds of for
loops that you’ll learn about later:
for-in
loopsfor-each
loops
You’ll study for-in
loops in Chapter 12, “Lists”, and for-each
loops in the “Anonymous Functions” chapter of Dart Apprentice: Beyond the Basics.
Exercise¶
- Write a
for
loop starting at1
and ending with10
inclusive. - Print the square of each number.
Challenges¶
Before moving on, here are some challenges to test your knowledge of loops. It’s best if you try to solve them yourself, but solutions are available in the challenge
folder if you get stuck.
Challenge 1: Next Power of Two¶
Given a number, determine the next power of two above or equal to that number. Powers of two are the numbers in the sequence of 2¹, 2², 2³, and so on. You may also recognize the series as 1, 2, 4, 8, 16, 32, 64…
Challenge 2: Fibonacci¶
Calculate the nth Fibonacci number. The Fibonacci sequence starts with 1, then 1 again, and then all subsequent numbers in the sequence are simply the previous two values in the sequence added together (1, 1, 2, 3, 5, 8…). You can get a refresher here: https://en.wikipedia.org/wiki/Fibonacci_number
Challenge 3: How Many Times?¶
In the following for
loop, what will be the value of sum
, and how many iterations will happen?
var sum = 0;
for (var i = 0; i <= 5; i++) {
sum += i;
}
Challenge 4: The Final Countdown¶
Print a countdown from 10 to 0.
Challenge 5: Print a Sequence¶
Print the sequence 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0
.
Key Points¶
while
loops perform a certain task repeatedly as long as a condition is true.do-while
loops always execute the loop at least once.for
loops allow you to perform a loop a set number of times.- The
break
statement lets you break out of a loop. - The
continue
statement ends the current iteration of a loop and begins the next iteration.