The FizzBuzz Problem

This is my take on a rather amusing coding assignment given to me by an acquaintance who had employed it as a baseline when recruiting programmers in the past. (Apparently it is a somewhat common screening method for such situations.) To be clear, I wasn't applying for anything; I did it simply for fun.

The idea of the assignment is to write a program that

  • outputs a sequence of increasing integers from 1 to 100;
  • substitutes each number divisible by three with Fizz;
  • substitutes each number divisible by five with Buzz;
  • substitutes each number divisible by three and five with FizzBuzz.

I have been dabbling with microcontrollers recently, so I decided to program this in Arduino IDE (which is based on C++). I added to the code some bells and whistles that relate to that particular format — in this case a couple of parameters for a tri-color LED:

  • Fizz triggers a red light;
  • Buzz triggers a blue light;
  • FizzBuzz triggers a green light.

(Obviously, the LED needs to be connected to an Arduino board accordingly, through a breadboard or a similar application.) The numbers themselves are printed in the serial monitor in one second intervals.

void setup() {
  Serial.begin(9600);
}

void loop() {
  for(int printNumber = 1; printNumber<101; printNumber++){
    delay(1000);

    if(printNumber % 3 == 0 && !(printNumber % 5) == 0){
      Serial.print("Fizz");
      Serial.println();
      digitalWrite(2, LOW);
      digitalWrite(3, LOW);
      digitalWrite(4, HIGH);
    }
    if(printNumber % 5 == 0 && !(printNumber % 3) == 0){
      Serial.print("Buzz");
      Serial.println();
      digitalWrite(2, LOW);
      digitalWrite(3, HIGH);
      digitalWrite(4, LOW);
    }
    if(printNumber % 3 == 0 && printNumber % 5 == 0){
      Serial.print("FizzBuzz");
      Serial.println()
      digitalWrite(2, HIGH);
      digitalWrite(3, LOW);
      digitalWrite(4, LOW);
    }  
    if(!(printNumber % 3) == 0 && !(printNumber % 5) == 0){
      Serial.print("");
      Serial.println()
      digitalWrite(2, LOW);
      digitalWrite(3, LOW);
      digitalWrite(4, LOW);
    }
  }
}

I thought that this was a very pedagogically sound, fun exercise for a beginner programmer. The answer wasn't overly obvious for a novice, and formulating it felt — to me at least — like a genuine accomplishment.

It could be argued that programming in general is a near-perfect form of enquiry-based learning, because it isn't restricted to any specific solution, instead encouraging and rewarding different approaches. For someone who wasn't taught any programming during elementary or comprehensive school, learning it later in life (even if at a very basic level) has been an incredibly rewarding experience.

More from M.
All posts