FizzBuzz project: Fizz, Buzz, and FizzBuzz not outputting correctly

Hi, I’m currently working on the FizzBuzz project in the C++ course. I think I’ve implemented the code correctly, (or am on the correct path to doing so), but I’m running into an issue where it outputs as followed:

1
2
3
Fizz
4

…and so on.

If I implemented the code correctly then 3 should be replaced with Fizz and the other numbers should also be replaced accordingly. Is there an issue with the way I coded this? Here’s my code from the project:

#include <iostream>

int main() {

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

  std::cout << i << "\n";

    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";

    }

    else {

      std::cout << i << "\n";

    }

 }

}

Thank you

@typa98,

Welcome to the forums!

Check out what your code does immediately before your if-else statements.

Happy coding!

2 Likes

Now that you’ve pointed it out, I can see why the code was failing. Thank you for your help.

On a different note, does i = 15 output “FizzBuzz”? Because it seems like the first if would also be true?

1 Like

Instead of checking for 15, check for 3 AND 5 in the same expression. Otherwise you will get a false positive on large enumerations.

This was what I originally did on this site, but it fails on other sites with more strict condtionsl

#include <iostream>

using namespace std;

int main()
{
  for (int i = 1; i <= INT8_MAX; ++i)
    if (i % 3 == 0)
      cout << "Fizz" << endl;
    else if (i % 5 == 0)
      cout << "Buzz" << endl;
    else
      cout << i << endl;
  return 0;
}
1 Like

It actually does not output FizzBuzz at 15 for me. There’s likely something I’m still missing but I’ll figure it out once I have some time later today

1 Like