FizzBuzz, one of the most well-known coding questions, and one of the most simple, yet unsimple? For many who are used to coding -- even at a beginner’s level -- should be able to accurately solve the FizzBuzz question in a matter of seconds even if they’ve never heard it before. In case you haven’t heard of the FizzBuzz coding question, the question just asks you to write a program that when called, prints every number from 1 to 100 but every multiple of 3 it prints “Fizz”, every multiple of 5 it prints “Buzz”, and every multiple of 15 it prints “FizzBuzz”. Although easy in the eyes of programmers, it may be a bit hard if you’ve never programmed before.
Now that you’ve gotten past the introduction, let’s see a common solution for this question. Note that I’ll be doing this in python (programming language).
First, we will start off with a for loop, which is exactly what the name implies: a loop.
for x in range (1, 100 + 1): # Here, I’m setting a loop that loop a hundred times.
Then, let’s put our conditional statements which are just statements that when true, run what’s inside. For example:
x = 1 If x == 1: print(“x is 1”) elif (x == 2): print(“x is 2”) else: print(“x is not 1 or 2”)
Here we are checking if the variable x is 1 in the if statement and if that statement is false, then we are check if x is 2. If both are false, we can be sure that x isn’t 1 or 2 so we return “x is not 1 or 2.” This returns “x is 1” because x is declared as 1 above. However, in our case, we want to check if “x” is a multiple of 3, multiple of 5, or multiple of both (15). We can go about this by writing this simple code.
for x in range (1, 100 + 1): # loop through 100 If (x % 3 == 0): # check if x is a multiple of 3 print(“Fizz”) elif (x % 5 == 0): # check if x is a multiple of 5 print(“Buzz”) elif (x % 15 == 0): # check if x is a multiple of 15 print(“FizzBuzz”) else: print(x)
This program might seem right, but if you run it, you’ll see that “FizzBuzz” isn’t getting printed anywhere. Why is that? It’s because this program checks if the “x” is a multiple of 3 or 5 first, and then a multiple of both. So, if x was 30, it would be a multiple of 15, but because the program checks for 3 first, it would print “Fizz.” We can easily fix this problem by changing the order of what the conditional statements check.
for x in range (1, 100 + 1): If (x % 15 == 0): # originally this checked if “x” was a multiple of 3. print(“Fizz”) elif (x % 5 == 0): print(“Fizz”) elif (x % 3 == 0): # originally this checked if “x” was a multiple of 15. print(“Buzz”) else: print(x):
Python Exercise: Get Fizz, Buzz and FizzBuzz https://www.w3resource.com/python-exercises/python-conditional-exercise-10.php FizzBuzz: One Simple Interview Question https://www.youtube.com/watch?v=QPZ0pIK_wsc