Writing "else if" between the lines would not work... in this order. Consider the case where the number is 45. The first test would evaluate to true and it would print "Fizz", yet it should have printed "FizzBuzz".
The proper else-if based approach would be to test the 3+5 case first, then hit 3 and 5 separately with else-ifs.
Another strategy is to check 3 then 5 with if statements and not worry about 3+5. If a number is divisible by both, "FizzBuzz" gets printed since they both triggered. The issue there, of course, is that you have to put the newline at the end of the loop block, not in the print statements.
I had to complete this question a couple times in my interviews fresh out of university, so I've given it a fair bit of thought.
After reading your explanation then rereading problem I completely see where I went wrong. Thank you for explanation and even showing two separate ways.
View all comments
Show parent comment
2
u/ActionScripter9109 my old code = timeless gems, theirs = legacy trash Jan 16 '14
Writing "else if" between the lines would not work... in this order. Consider the case where the number is 45. The first test would evaluate to true and it would print "Fizz", yet it should have printed "FizzBuzz".
The proper else-if based approach would be to test the 3+5 case first, then hit 3 and 5 separately with else-ifs.
Another strategy is to check 3 then 5 with if statements and not worry about 3+5. If a number is divisible by both, "FizzBuzz" gets printed since they both triggered. The issue there, of course, is that you have to put the newline at the end of the loop block, not in the print statements.
I had to complete this question a couple times in my interviews fresh out of university, so I've given it a fair bit of thought.