Quick question on FizzBuzz and if else statements

Hello everybody, my first time through this exercise I wrote the for loop like this:

for (int i = 1; i <= 100; i++) {

  if (i % 3 == 0) {

System.out.println("Fizz");

  } else if (i % 3 == 0 && i % 5 == 0) {

System.out.println("FizzBuzz");

  } else if (i % 5 == 0) {

System.out.println("Buzz");

  } else {

System.out.println(i);

  }

It wasn’t outputting FizzBuzz even though the syntax for the if statement and modulo was right. So I switched the if statement to check if the i variable is divisible by 5 and 3 first, then it printed out FizzBuzz, Fizz, and Buzz correctly.

for (int i = 1; i <= 100; i++) {

  if (i % 3 == 0 && i % 5 == 0) {

System.out.println("FizzBuzz");

  } else if (i % 3 == 0) {

System.out.println("Fizz");

  } else if (i % 5 == 0) {

System.out.println("Buzz");

  } else {

System.out.println(i);

  }
}

My question is why does the if statement for FizzBuzz with both modulos have to be inputted first for the program to work correctly? Why does the program not print FizzBuzz even though it is still in an if-statement and still in the for loop?

Let take a number which is FizzBuzz (like 15), so 15 arrives at the if condition:

if (15 % 3 == 0)

which is true, so Fizz is printed, given the if condition is true, the remaining conditions are skipped.

Thank you for the explanation!

Barely explained anything?

Anyway, the steps I just did, is something you should teach yourself :slight_smile: far more important then this specific thing you now know :wink:

1 Like

You’re right, I will definitely practice more with loops/if statements.

Not just that, but the ability to walk/step through your code in your mind :wink: To help you debug :slight_smile:

Yes! That’s probably the most difficult thing for me at this point is thinking about each step and visualizing how the code works through the program. I’ll try to consciously think about it every time.

1 Like

There are also tools to help you with this process:

http://www.pythontutor.com/visualize.html#mode=edit

a debugger on your IDE/text-editor

2 Likes

That’s so awesome thank you! Very helpful