Help with FizzBuzz.cpp - order of code

Hi

I am working on FizzBuzz.cpp, my code is correct but in a different order to the version on GitHub, see;

learn-cpp/fizzbuzz.cpp at master · Codecademy/learn-cpp · GitHub

My code can be found at this URL;

Learn C++ | Codecademy

Or see below;

#include <iostream>

int main() {

//Brain explodes here


for (int i= 1; i <= 100; i++) {

if (i % 3 == 0) {

  std::cout << "Fizz\n";
}
else if (i % 5 == 0){

  std::cout << "Buzz\n";
}
else if (i % 15 == 0) {

  std::cout << "FizzBuzz\n";
}
else {

  std::cout << i << "\n";
}
}
return 0;
}

I’d really like to understand why the order makes a difference :slight_smile:

Thank you in advance

Hey there, and welcome to the forums!

The order matters here specifically because the block is if-else if. When an if statement is evaluated, it goes down in order of the code as written. In addition, else if blocks will not run if the previous block conditions have been met.

In this case, by definition anything that is perfectly divisible by 15 must also be divisible by 3 and 5. Therefore when you reach a number that should be “FizzBuzz”, say 15, it checks if that number is divisible by 3 first. Since this is true, it prints “Fizz”, and then skips all the other else if blocks as the if statement has been completed. Therefore you want to check if it is divisible by 15 first, otherwise it’ll never be reached.

1 Like

Ok, thanks adamgaffney96, this makes sense. I just could not get my head round the reason, I think I was staring at it for too long!

Thank you for helping me understand C++ better :slightly_smiling_face