Why isn't my FizzBuzz code processing both if statements when they both match?

3.8k Views Asked by At

For those who don't know, FizzBuzz is the following problem:

Write a program that prints the numbers from 1 to 100. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz".

Every FizzBuzz solution I find is either some crazy esoteric solution made for the sake of being original, or your basic if-else chain:

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

    if(i % 3 == 0 && i % 5 == 0) {
       System.out.println("FizzBuzz");
    } else if (i % 3 == 0) {
       System.out.println("Fizz");
    } else if (i % 5 == 0) {
       System.out.println("Buzz");
    } else {
       System.out.println(i);
    }
}

I am looking for a simple solution that aims to take out the "FizzBuzz" if statement. I have this in mind:

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

    if (i % 3 == 0) 
       System.out.print("Fizz");
    if (i % 5 == 0) 
       System.out.println("Buzz")
    else
       System.out.println(i);
}

But this doesn't work. I assume it would be able to print FizzBuzz by entering both ifs, for Fizz and for Buzz, but if the number is, for example, 3, it would print Fizz3. How do I avoid this?

9

There are 9 best solutions below

5
On BEST ANSWER

What you're trying to do is

if (a)
    ...
if (b)
    ...
else // if neigther a nor b
    ...

This is simply not possible. An else can only belong to a single if. You have to go with the slightly longer variant.

To avoid doing redundant evaluations of the modulo operator, you could formulate the loop body as

boolean fizz = i % 3 == 0;
boolean buzz = i % 5 == 0;

if (fizz) 
   System.out.print("Fizz");
if (buzz)
   System.out.print("Buzz");
if (!(fizz || buzz))
   System.out.print(i);

System.out.println();

Another one would be

String result = "";

if (i % 3 == 0)   result = "Fizz";
if (i % 5 == 0)   result += "Buzz";
if (result == "") result += i;

System.out.println(result);
3
On

If your only goal is to avoid using &&, you could use a double negation and DeMorgan's laws:

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

    if(!(i % 3 != 0 || i % 5 != 0)) {
       System.out.println("FizzBuzz");
    } else if (i % 3 == 0) {
       System.out.println("Fizz");
    } else if (i % 5 == 0) {
       System.out.println("Buzz");
    } else {
       System.out.println(i);
    }
}

You can avoid && using the fact that i % 3 == 0 and i % 5 == 0 implies i % 15 == 0, as per RFC1337's answer.

Another solution is to use a switch on the remainder (mod 15, which is 5 times 3):

for(int i = 1; i <= 100; i++) {
    final int mod = i % 15;
    switch (mod) {
        case 0:
        case 3:
        case 6:
        case 9:
        case 12:
            System.out.print("Fizz");
            if (mod != 0) break;
        case 5:
        case 10:
            System.out.print("Buzz");
            break;
        default:
            System.out.print(i);
    }

    System.out.println();
}
2
On

Your first if statement is all alone.

So, your code hits the first statement, which is ONLY an if statement, and then goes on to the next, which is an if/else statement.

RosettaCode has a good example without using AND operators.

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

Don't use an if statement at all.

import java.util.*;
import java.lang.*;
import java.io.*;
class FizzBuzz
{
    public static void main (String[] args) throws java.lang.Exception
    {
        String[] words = {"", "Fizz", "Buzz"};
        String[] nwords = {"", ""};

        for(int i = 1; i < 101; ++i)
        {
            int fp = (i % 3 == 0) ? 1 : 0;
            int bp = ((i % 5 == 0) ? 1 : 0) * 2;
            int np = ((fp > 0 || bp > 0) ? 1: 0);

            nwords[0] = Integer.toString(i);

            System.out.print(words[fp]);
            System.out.print(words[bp]);
            System.out.println(nwords[np]);
        }
    }
}

See it on ideone.

0
On

Just add a flag variable and use System.out.print:

package com.stackoverflow;

public class FizzBuzz {
    public static void main(String[] args) {
        for (int i = 1; i <= 100; i++) {
            boolean printed = false;
            if (i % 3 == 0) {
                printed = true;
                System.out.print("Fizz");
            }
            if (i % 5 == 0) {
                printed = true;
                System.out.print("Buzz");
            }

            if (printed) {
                System.out.println();
            } else {
                System.out.println(i);
            }
        }
    }
}
0
On
public class fizzbuzz 
{

    public static void main(String[] args) 
    {
        String result;
        for(int i=1; i<=100;i++)
        {    
            result=" ";
            if(i%3==0)
            {
                result=result+"Fizz";
            }
            if(i%5==0)
            {
                result=result+"Buzz";
            }
            if (result==" ")
            {
                result=result+i;
            }
            System.out.println(result);
        }
    }

}

This is the most efficient way I could come up with. Hope it helps! :)

1
On

Crazy albeit unrelated solution done in Python3

#!/usr/bin/python3

for i in range(1,100):
    msg = "Fizz" * bool(i%3==0)
    msg += "Buzz" * bool(i%5==0)
    if not msg:
        msg = i
print(msg)
0
On

This doesn't take out the if statements but does not use the && (and) operator, you could flip the binary operators.

//FizzBuzz Case
if(!(a % 3 != 0 || a % 5 != 0)){ //flips 
  result[index] = "FizzBuzz";
  index++;
  }
0
On

This is my solution. Granted, it's a bit convoluted (as in roundabout), but I believe it suits your requirement.

int main()
{
    char fizzpass=0;

    unsigned short index=0;

    for(index=1;index<=100;index++)
    {
        if(0 == (index%3))
        {
           printf("Fizz");
           fizzpass = 1;
        }

        if(0 == (index%5))
        {
           if(1 == fizzpass)
           {                  
              fizzpass = 0;
           }

           printf("Buzz\n"); 
           continue;
        }

        if(1 == fizzpass)
        {
            fizzpass = 0;
            printf("\n");
            continue;
        }

        printf("%d\n",index);
    }

    return 0;
}

Regards.