vendredi 1 mai 2020

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

}

}

Aucun commentaire:

Enregistrer un commentaire