Search code examples
c++loopsif-statementincrement

C++: stopping last increment in my Fizz Buzz program


So as part of a coding challenge I tried to make a Fizz Buzz program in C++ without looking at the solution. For those of you who don't know, it should be a loop that replaces any number divisible by 3 with Fizz, any number divisible by 5 with Buzz, and any number divisible by both with FizzBuzz:

1
2
Fizz
4
Buzz
6
7
8
Fizz
Buzz
11
Fizz

I'm almost there with the code below, however, i'm a little annoyed that even though I want the loop to stop entirely at 100, the way i've set up the program means that an extra 1 gets added to i after the loop has ended. Is there a way of stopping my FizzBuzz program from going past 100?

#include <iostream>

using namespace std;

int main () {

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

if (i % 3 == 0 && i % 5 == 0){
    cout << "FizzBuzz\n";
    i = i + 1;
}

if (i % 3 == 0){
  cout << "Fizz\n";
  i = i + 1;
}

if (i % 5 == 0){
  cout << "Buzz\n";
  i = i + 1;
}

cout << i << "\n";

}

}

Solution

  • So I fixed your code a little bit:

    int main()
    {
        for (int i = 1; i < 101; ++i)
        {
           if (i % 3 == 0 && i % 5 == 0)
                cout << "FizzBuzz\n";
            else if (i % 3 == 0)
                cout << "Fizz\n";
            else if (i % 5 == 0)
                cout << "Buzz\n";
            else
                cout << i << "\n";
    
        }
    
    }
    

    Every time you do i = i + 1;, it's kinda useless because your loop does that. Also, I put everything is an if else chain, instead of and if if chain. That way only on statement will execute at any giving time. Also changed the max to 101 instead of 100 since the for loop will stop at 101 and not print the result of 101.

    Hope this helps :)