Lab 5: FizzBuzz

In this hands-on activity we will be programming the FizzBuzz game, a common programming interview question.

Example

There is this party game for children called "fizz buzz." The way it works is the first child says "one" and the second child says "two" and so on around the circle, counting up as they go. However, on a multiple of three, a child is supposed to say "Fizz!" instead. If a child ever says the wrong thing, they are out!

A harder version (which we'll see later) has an extra rule: on a multiple of five, you say "Buzz!" This means on a multiple of fifteen, you would say both words, yielding "FizzBuzz!"

For example, in JavaScript:

// Input Variables
var num = 7;

// Let's play the game!
for (var i=1; i <= num; ++i){
    if (i % 3 == 0){
        console.log("Fizz!");
    } else {
        console.log(i);
    }
}

// Result:
// 1
// 2
// Fizz!
// 4
// 5
// Fizz!
// 7

Questions

Part 1

  1. What does the "mod" or "modulo" operator mean in programming?
  2. Answer for each language: What is the syntax for an if/else statement in your language that checks whether a variable is a multiple of some number? How could you use this to check if 125 is a multiple of 7, displaying "YES" if it is or "NO" if it's not? Demonstrate your answer with screenshots.
  3. True or false and explain: Every if must be followed by an else.
  4. True or false and explain: Every else must immediately follow an if (or elif).
  5. In programming, what does the word "nesting" mean when talking about control structures?
  6. Answer for each language: What is the syntax in your language for nesting an if/else inside of a for loop? How would you use this to visit each number from 1 to 10 (inclusive), display that number if it is a multiple of three, and otherwise display a blank line? (Like the example output below)
blank
blank
3
blank
blank
6
blank
blank
9
blank

Part 2

  1. Pick one language from your group. What language did you choose for this task and why?
  2. In your chosen language, program the fizzbuzz game described above. Change the value of the num variable to 20 and make it display "Fizz!" on multiples of four instead. Demonstrate your answer with screenshots.

Part 3

For each of the following, revise your fizzbuzz game to help you find the answer, and demonstrate with screenshots.

  1. How many multiples of 4 are there between 1 and 15 (inclusive)?
  2. How many multiples of 4 are there between 1 and 50 (inclusive)?
  3. In the harder version of the fizzbuzz game (say "Fizz!" on multiples of three and "Buzz!" on multiples of five, but "FizzBuzz!" on multiples of fifteen), if you are counting up to 100 (inclusive):
    • How many times would you say "Fizz!"?
    • How many times would you say "Buzz!"?
    • How many times would you say "FizzBuzz!"?

(Hint: You may find the RosettaCode page on FizzBuzz helpful for this last question.)