My Byte of Code Blog. Tips and observations on creating software with Objective-C, C/C++, Python, Cocoa and Boost on Mac.

Tuesday, February 23, 2010

My FizzBuzz Solution In C++

If you are not sure if I can write simple code here is my FizzBuzz c++ solution:

#include <iostream>
using namespace std;

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

And the output for the first 15 values:

1
2  
Fizz
4  
Buzz
Fizz
7  
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz

I guess this proves that I probably am compulsive problem solver. In my defence I was pointing someone else at the idea behind FizzBuzz and I couldn't resist to put down a few lines of code that produced the desired output ...


3 comments:

  1. Um, the actual game involves substituting "fizz", "buzz" and "fizzbuzz" for the numbers in the proper places, not adding them.

    Here:

    int main()
    {
    bool flag;
    for (int i = 1; i < 101; ++i)
    {
    flag = true;
    if (i % 3 == 0)
    {
    cout << "Fizz";
    flag = False;
    }
    if (i % 5 == 0)
    {
    cout << "Buzz";
    flag=False;
    }
    if (flag == True)
    {
    cout << i << " ";
    }
    cout << endl;
    }
    }

    That fixes your code. It uses a flag to note if fizz or buzz was written and, if not, writes the integer.

    An alternative is to test for mod 3 or mod 5 all at once (i.e. i%3==0||i%5==0 or even (i%3)*(i%5)==0). I think flipping a bit is more elegent than performing redundant math, but that is just my opinion.

    ReplyDelete
  2. I tried to be smart and show the index numbers to confirm that it shows the text at correct positions. But after double checking the original task I admit the index numbers should be replaced. Example updated. Thanks for pointing it out. Have fun :)

    ReplyDelete
  3. My solution:


    #include
    using namespace std;
    int main(){

    int x = 0;
    for(x= 1; x<50; ++x){
    if (x % 3 == 0){
    cout <<"fizz";
    }

    if (x % 5 == 0){
    cout <<"buzz";
    }

    if(x % 3 != 0 && x % 5 != 0){
    cout <<x;
    }
    cout <<endl;
    }
    }

    ReplyDelete