Lesson 2 · Unit 02
Loops
while, for, loop, break and continue, traced round by round
What you practise
loop,while,forover a range,breakandcontinue,breakwith 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?
let mut n = 1;
while n <= 3 {
println!("{n}");
n += 1;
}Correct answer
1, 2, 3
Why
Each round prints n and then adds 1 to it. After the third round n is 4, the test 4 <= 3 is false, and the loop ends without printing 4.
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.
let mut n = 1; // n: 1, 2, 3, 4
while n <= 3 { // true 3 times
n += 1;
}
println!("{n}"); // prints 4Concept
`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.
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.
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.