8

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?

Ryan M
  • 18,333
  • 31
  • 67
  • 74
bpromas
  • 684
  • 1
  • 11
  • 25

9 Answers9

10

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);
aioobe
  • 413,195
  • 112
  • 811
  • 826
3

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();
}
Community
  • 1
  • 1
Platinum Azure
  • 45,269
  • 12
  • 110
  • 134
  • just store i%15 at the top rather than calculating the modulo twice. – Randall Hunt Oct 02 '12 at 03:15
  • Is there a performance penalty of declaring a final variable over and over again? I seem to remember running into that years and years ago but I can't find any reference to it now. – Randall Hunt Oct 02 '12 at 18:28
  • I wasn't aware of anything like that. I figured compilation would take a little longer in order to ensure that the value isn't reassigned in the same scope, but I figured the compiler could also perform some optimizations based on the variable being `final`. I usually use `final` where I can. – Platinum Azure Oct 02 '12 at 19:00
3

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;
   }
RFC1337
  • 167
  • 1
  • 7
  • 1
    I think the intention was to reuse the `Fizz` when writing `FizzBuzz`. – aioobe May 16 '12 at 14:14
  • 1
    @aioobe Yeah, and I think this could be easily adapted with a little more nesting of conditionals. I was going to suggest a switch case, but [Platinum Azure](http://stackoverflow.com/a/10620230/1397668) Already provided an example for that. – RFC1337 May 16 '12 at 15:03
1

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.

0

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

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++;
  }
TheArchon
  • 313
  • 5
  • 15
0

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
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! :)

Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
saatweek
  • 13
  • 5
-3

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)
Harrison-SC
  • 7
  • 1
  • 4