## Dart Apprentice: Fundamentals

First Edition · Flutter · Dart 2.18 · VS Code 1.71

# 6. Loops Written by Jonathan Sande

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

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.

``````do {
// loop code
} while (condition)
``````
``````var sum = 1;
do {
sum += 4;
print(sum);
} while (sum < 10);
``````

### 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');
``````
``````var sum = 0;
do {
sum += (1 + 3 - 2 * 4 + 8);
} while (sum < 10);
print('do-while loop sum: \$sum');
``````

### 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.

``````sum = 1;
while (true) {
sum += 4;
if (sum > 10) {
break;
}
}
``````

### Exercise

• Create a variable named `counter` and set it equal to `0`.
• Create a `while` loop with the condition `counter < 10`.
• The loop body should print out “counter is X” (where X is replaced with the value of `counter`) and then increment `counter` 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.

``````for (var i = 0; i < 5; i++) {
print(i);
}
``````
``````0
1
2
3
4
``````

### 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);
}
``````
``````0
1
3
4
``````

### More For Loops

There are two more kinds of `for` loops that you’ll learn about later:

### Exercise

• Write a `for` loop starting at `1` and ending with `10` 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.
Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.

You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now