Boss lesson · Unit 02
FizzBuzz and friends
Loops and conditions together, and the off-by-one error
What you practise
- Loops and conditions together: FizzBuzz, summing digits, testing for a prime, the off-by-one error found and fixed
Try a question from this lesson
Pick one
FizzBuzz: count up from 1. Say Fizz for multiples of 3, Buzz for multiples of 5, FizzBuzz for both, else the number. What is said at 15?
Correct answer
FizzBuzz
Why
15 is 3 times 5, so it is a multiple of both and gets the combined word. The game sounds trivial, and yet the first program most people write for it has a bug.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
Most special case first
In a chain, an early test can swallow a later one. Put the narrowest test at the top.
"Multiple of 3 and of 5" can also be written the way you say it, with &&.
let n = 30;
let both = n % 3 == 0 && n % 5 == 0;
println!("{both}");
println!("{}", n % 15 == 0);Concept
Taking a number apart
Two old friends split a number into digits.
n % 10 is the last digit: what is left after taking out all the tens.
n / 10 removes the last digit: whole-number division drops it.
Repeat both until nothing is left, and you have visited every digit.
let n = 472;
println!("{}", n % 10);
println!("{}", n / 10);10 more exercises in the app
- 3× multiple choice
- 2× fill the blanks
- 1× order the lines
- 3× type the answer
- 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.