Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.


1,519 Points

FizzBuzz Exercise in Control Flow

Why does the below:

if ((i % 3 == 0) && (i % 5 == 0)) { print("FizzBuzz") }

need to appear first in the if else statement, why not the below statement first:

if ((i % 3 == 0) { print("Fizz") }

2 Answers

Jennifer Nordell
Jennifer Nordell
Treehouse Teacher

Hi there, Jed Odagbu ! In addition to Michael Hulet 's great answer, I thought I'd provide a concrete example. Remember, that in the case of an if / else if / else structure that only one condition will be met and run. At the moment that condition is met, it executes that code and doesn't check any further.

So let's say we start with 1 and go up to 20. We start by checking if the number is divisible by 3, then we check if it's divisible by 3 and 5 (as you have stated). We get to 3 and we get back a "Fizz" because it's divisible by 3. We get to 5 and get back "Buzz" because that's divisible by 5. We get to 6 and get back "Fizz" because it's divisible by 3. We get to 9 and it's divisible by 3 etc etc... and it all works just fine until we get to 15.

When we get to 15, if we had code that first checks if it's divisible by 3, it will return/print "Fizz" because it's divisible by 3. But then it will stop checking and move onwards to 16. But it definitely should be printing "FizzBuzz" as 15 is divisible by 15. Thus, you need to place the check for if it's divisible by 3 and 5 first.

Hope this helps! :sparkles:

Michael Hulet
Michael Hulet
Treehouse Moderator 47,822 Points

You'll first need to check if it's a multiple of both 3 and 5 first because doing so guarantees that "FizzBuzz" will be printed if it's divisible by both 3 and 5, as opposed to just "Fizz", just "Buzz", or both "Fizz" and "Buzz" but on 2 separate lines