Boss lesson · Unit 02
FizzBuzz and friends
Loops and conditions together: FizzBuzz, digit sums, primes 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
A number divides evenly by 3 when the remainder is 0. Which numbers does this print, one per line?
for i := 1; i <= 10; i++ {
if i%3 == 0 {
fmt.Println(i)
}
}Correct answer
3 6 9
Why
i%3 is the remainder after dividing by 3. It is 0 for 3, 6 and 9, so only those pass the if. The loop stops after 10, so 12 is never reached.
The ideas
Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.
Concept
The FizzBuzz problem
A famous small test for programmers. For every number from 1 to 15, print one line:
"Fizz" if the number divides by 3, "Buzz" if it divides by 5, "FizzBuzz" if it divides by both, and otherwise the number itself.
It needs nothing new: a loop, % and a chain of ifs. The only trap is the order of the questions.
1
2
Fizz
4
Buzz
Fizz
7
...
14
FizzBuzzConcept
Taking a number apart
Two small moves take a whole number apart, digit by digit. n % 10 is its last digit. n / 10 is the number without its last digit, because whole-number division drops the remainder.
Repeat both in a loop until nothing is left, and you have visited every digit.
n := 472
fmt.Println(n % 10) // 2
fmt.Println(n / 10) // 4710 more exercises in the app
- 3× multiple choice
- 2× fill the blanks
- 3× type the answer
- 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.