Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

jedodagbu
jedodagbu
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
seal-mask
STAFF
.a{fill-rule:evenodd;}techdegree
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
47,912 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