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
Lorenzo Pieri
19,772 PointsIntruduction to Programming (EXTRA for Loops)
Good day! I was trying to achieve the EXTRA thingie at the INTRODUCTION TO PROGRAMMING - Control Structures.
I was setting this code in the console:
for ( var i = 0; i <= 100; i++) {
if( i % 3 == 0) {console.log("Fizz");}
else if( i % 5 == 0) {console.log("Buzz");}
else if( i % 3 == 0 && i % 5 == 0) {console.log("FizzBuzz!");}
else {
console.log(i);
}
}
But it didnt work. I went for a stupid solution such as:
for ( var i = 0; i <= 100; i++) {
if( i % 3 == 0) {
if( i % 5 == 0) {
console.log("FizzBuzz!");
} else {
console.log("Fizz");
}
}
else if( i % 5 == 0) {console.log("Buzz");}
else {
console.log(i);
}
}
Any ideas on why the AND isnt working over there? :\
2 Answers
Charlie Knight
4,338 PointsIt looks like your condition is in the wrong place. If you place the AND statement as the first condition and the other conditions lead off that, then it will work.
Take 15. Reading your code. Am I divisible by 3? Yes - Execute "Fizz". That's it - it met a condition and the other statements are ignored. So change your code too
for ( var i = 0; i <= 100; i++) {
if( i % 3 == 0 && i % 5 == 0) {console.log("FizzBuzz!");}
else if (i % 3 == 0) { console.log("Fizz");}
else if( i % 5 == 0) {console.log("Buzz");}
else {
console.log(i);
}
That should work. Hope this helps.
Lorenzo Pieri
19,772 PointsI don't even know how much dumb can I be for not thinking in such a way. The teacher's right, we have to think like computers, not like humans. Dammit. Thank you man!
Lorenzo Pieri
19,772 PointsLorenzo Pieri
19,772 PointsSorry for not giving you the best answer the moment you wrote! I thought I just needed to upvote you XD Thanks to Treehouse for letting me know by e-mail, and thank you for helping me out! :)