print a list of numbers, replace numbers with words multiples of 3,5 also 3and5 C

Non_Trad_Nick picture Non_Trad_Nick · Oct 24, 2013 · Viewed 21.9k times · Source

Had my midterm in "programming with C" last week, the final question was write a program to print a list of numbers from 1 - 100 but every multiple of 3 print fizz, multiple of 5 buzz, and multiple of 3 and 5 print fizzbuzz. Just got my grade I got a 76% and I am sure I got every other question right, so I must have had errors in my code. I am trying to figure it out (cannot remember what I wrote on paper) My problem is that I basically have it working, but it is also printing the number, and the number should be replaced by the word. Here is the code I have so far.

#include <stdio.h>

int main (void)
{
        int x,y;
        printf("this should count from 1 to 100, and instead of printing the multiples of 3 or 5 or 3 and 5 it should print words\n");
        for (x=1; x<=100; x++)
        {
                if (x%3==0)
                {
                    printf("fizz\n");
                }
                if (x%5==0)
                {
                    printf("buzz\n");
                }
                if (x%3==0 && x%5==0)
                {
                    printf("FizzBuzz\n");
                }
        printf("%d\n",x);
        }
return 0;
}

I do not actually get to "re-take" the test or anything like that so I am not trying to cheat, I am just baffled as to what I need to do here. the output I get is

1
2
fizz
3
4
buzz
5
fizz
6
7
8
fizz
9
buzz
10
11
fizz
12
13
14
fizz
buzz
FizzBuzz
15
16

Where it should look like this:

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

Answer

jrd1 picture jrd1 · Oct 24, 2013

Your conditionals are wrong. They should be:

if (x%3==0 && x%5==0)
{
    printf("FizzBuzz\n");
}
else if (x%3==0)
{
    printf("fizz\n");
}
else if (x%5==0)
{
    printf("buzz\n");
}
else
{
    printf("%d\n",x);
}

Remember, it's FizzBuzz if both are divisible by 3 and 5, and Fizz if the number is divisible by 3, and Buzz if the number is divisible by 5.