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 Swift Basics (retired) Control Flow Exercise: FizzBuzz Generator

The Fizz/Buzz problem: What if the nr. is zero ?

I made up this code:

let a = 15
if a % 3 == 0 && a % 5 != 0 { print("Fizz") }
else if a % 3 != 0 && a % 5 == 0 { print("Buzz") }
else if a % 3 == 0 && a % 5 == 0 && a != 0 { print("Fizz Buzz") }
else if a == 0 { print("The Nr. is zero") }
else { print("NIL") }

2 Answers

Hi there,

I guess for zero, the output should be "FizzBuzz" as zero can be divided by both 3 and 5 (or any number except zero) without remainder.

If you test the "FizzBuzz" outcome first, then do the others in turn, you don't need to check for != 0 as that outcome has already occurred. The if statement will stop testing as soon as a positive outcome occurs so, test for a zero remainder with 3 && 5 first. That outcome is then excluded as a possibility for the subsequent tests. This simplifies the code as you don't need to add in the != scenario. I hope that makes sense!

Steve.

func fizzbuzz(#number: Int){
if number % 3 == 0 && number % 5 == 0 {
    println("FizzBuzz")
 } else if number % 5 == 0 {
    println("Buzz")
 } else if number % 3 == 0 {
    println("Fizz")
 } else {
    println("No fizzing, buzzing, or fizzbuzzing for you!")
 }
}

for var i = 0; i < 50; i++ {
    fizzbuzz(number: i)
}

Steve, thank you... but I just learned today the first course of functions. Thank you again for your reply.

No problem! Yes, I did add a function in my reply - that's what was in my Playground. I'm sure that'll make sense very quickly if the concept is new to you.

I think the main point I was making was the application of logical rules and why the order they are applied makes a difference, enabling simpler code involving fewer tests. The function piece and the loop aren't really relevant to that.

Good luck with the rest of the course(s) and just shout on the Community pages if you need help.

Steve.