Stuck on FizzBuzz exercise

Link to Exercise/Assignment: https://www.codecademy.com/courses/learn-c-plus-plus/projects/cpp-fizzbuzz

I need help with the FizzBuzz loop exercise since I’m so stuck that I don’t know what to do next.

Code:

int main() {

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

    std::cout << number << "\n";
    if (number % 3 == 0) {
      std::cout << "Fizz\n";
    }
    else if (number % 5 == 0) {
      std::cout << "Buzz\n";
    }
    else if (number % 3 == 0 && number % 5 == 0) {
      std::cout << "FizzBuzz\n";
    }
    else {
      std::cout << number << "\n";
    }

  }

}

In this code, I made it so that if a number is able to be divided by 3 or 5 or both it will print the following text (Fizz for 3, Buzz for 5, Fizzbuzz if it can be divided by 3 and 5). However, instead of the number being replaced by the text, the text is printed after the number (This is only for when the number can be divided by 3 or 5). I am not sure how to program the code to make it so the number will be replaced with the text instead of printing it after the number.

The part where it says if the number can be divided by 3 and 5 it will print Fizzbuzz but instead it doesn’t print out the text at all which makes me believe that some part of the code is interfering with it.

I would like someone to point out what exactly I am doing wrong with the code and how I can fix it.

The test for both should precede the test for each.

1 Like

Thank you, it fixed the problem with it not printing however the code now outputs two numbers when executed but doesn’t when the number can be divided by 3, 5, or both.

Output:

1
1
2
2
3
Fizz
4
4
5
Buzz
6
Fizz
7
7
8
8
9
Fizz
10
Buzz
11
11
12
Fizz
13
13
14
14
15
FizzBuzz
16
16
17
17
18
Fizz
19
19
20
1 Like

You have an extra std::cout before the if and else if stuff.

1 Like
#include <iostream>

int main() {

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

    std::cout << number << "\n";
    if (number % 3 == 0 && number % 5 == 0) {
      std::cout << "FizzBuzz\n";
    }
    else if (number % 5 == 0) {
      std::cout << "Buzz\n";
    }
    else if (number % 3 == 0) {
      std::cout << "Fizz\n";
    }

  }

}

Removed the std::cout from the bottom of the code and it fixed the problem. Thank you very much.