FizzBuzz: loops, % and decisions
Count from 1 to n, but say Fizz for multiples of 3, Buzz for multiples of 5 and FizzBuzz for multiples of both. Watch the remainder decide each number, and see why the order of the checks matters.
Core concept
A loop can make a decision on every repeat: i % 3 == 0 is true when 3 divides i exactly, and in a chain of ELSE IFs the first true check wins, so the most special case must come first
Topic: Loops and patterns
FizzBuzz is a counting game played in a circle: count 1, 2, 3 … but say Fizz instead of a number that 3 divides, Buzz instead of one that 5 divides, and FizzBuzz when both do. A program plays it with a FOR loop: Steps that repeat, either a set number of times or until something becomes true. All key words and a chain of decisions. To test “3 divides i” it uses the remainder: i % 3 is what is left after dividing i by 3, so i % 3 == 0 means there is nothing left over. The checks go in a chain: IF … ELSE IF … ELSE IF … ELSE. The computer tries them from the top and runs only the first one that is true, so the order of the checks matters.
What you will learn
- Use the remainder (%) to test whether one number divides another.
- Trace a loop that makes a decision on every repeat.
- Explain why the order of checks in an ELSE IF chain matters.
- Count how often each branch runs.
Before you start
- Know multiples and remainders, and how a FOR loop counts.
Materials
- A notebook to play the game on paper first
Equipment
- None
Procedure
- Run the program up to 15 and read what it says for each number.
- Step through some numbers and watch which check is true.
- Count up to 30 and see how many FizzBuzzes there are.
- Answer the practice challenges.