Bitpath

Lesson 2 · Unit 02

Loops

while, for, loop, break and continue, traced round by round

13 exercisesabout 3 min

What you practise

  • loop, while, for over a range, break and continue, break with a value, a running total, tracing a loop by hand

Try a question from this lesson

Pick one

while repeats its braces as long as the test is true. What does this print, top to bottom?

Rust
let mut n = 1;
while n <= 3 {
    println!("{n}");
    n += 1;
}

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

Tracing a loop

A while loop checks its test, runs its braces, and goes back to the test. When the test is false, the program carries on below the loop.

To understand a loop, trace it: write down each variable after every round. The notes on the right are a trace.

Rust
let mut n = 1;    // n: 1, 2, 3, 4
while n <= 3 {    // true 3 times
    n += 1;
}
println!("{n}");  // prints 4

Concept

`for` and ranges

Counting is so common that it has its own loop. for i in 1..4 runs its braces with i as 1, then 2, then 3.

1..4 is a range. The end is left out. Write 1..=4 to include the 4.

A for loop has no counting variable to forget, so it cannot run forever.

Rust
for i in 1..4 {
    println!("{i}");
}
for i in 1..=4 {
    println!("{i}");
}

Concept

`loop`, `break`, `continue`

loop repeats its braces forever, until a break.

break leaves the loop right now. continue skips the rest of this round and starts the next one.

Both also work inside while and for.

Rust
let mut n = 0;
loop {
    n += 1;
    if n == 3 { continue; }
    if n > 5 { break; }
    println!("{n}");
}

9 more exercises in the app

  • 3× type the answer
  • 2× multiple choice
  • 2× fill the blanks
  • 1× order the lines
  • 1× true or false

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy