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 trialBen Masel
2,004 PointsI do not really no what i am doing here!
I do not get what I'm doing wrong and i don't think i know what I'm doing as well!
func fizzBuzz(n: Int) -> String {
// Enter your code between the two comment markers
var n = 18
if (n % 3 == 0) {
print("Fizz")
}
// End code
return "\(n)"
}
1 Answer
Dave Berning
17,365 PointsHi Benjamin,
So the idea is to return a string of "Fizz" if a number is divisible by 3, "Buzz" if divisible by 5, and "FizzBuzz" if divisible by both. We can check that by using the remainder operator. If a number is divisible by 3, the remainder of that number will be zero.
We can check each number by using an if-else statement. In if-else statements and switch cases, which ever statement is correct first will get executed; everything else won't. So it's important to write your "FizzBuzz" conditional first.
func fizzBuzz(n: Int) -> String {
// Enter your code between the two comment markers
if (n % 3 == 0) && (n % 5 == 0) {
return "FizzBuzz"
} else if n % 3 == 0 {
return "Fizz"
} else if n % 5 == 0 {
return "Buzz"
}
// End code
return "\(n)"
}
Hope this helps, Dave
Ben Masel
2,004 PointsI completely forgot the if statements!
Ben Masel
2,004 PointsI just want to check, were we supposed to do 5 and 3 or could we do whatever Integers we liked?
Dave Berning
17,365 PointsYou're supposed to use 3 and 5; it cannot be which ever integer you want. I've done this as an exercise at the University of Cincinnati, so this isn't just a Treehouse original exercise. The idea behind using 3 and 5 is to make sure you are printing "FizzBuzz" when a number is divisible by both. 15 for example is divisible by both 3 and 5. If you print out "Fizz" or "Buzz" for 15 it'll be wrong. It has to be "FizzBuzz".
This exercise is to illustrate the importance of the position of your if and switch case statements.
So for example...
1, 2, Fizz (3), 4, Buzz (5), Fizz (6), 7, 8, Fizz (9), Buzz (10), 11, Fizz (12), 13, 14, FizzBuzz (15).
Ben Masel
2,004 PointsBen Masel
2,004 PointsThank you so much!