4

Fizz Buzz in Every Language

 3 years ago
source link: https://dev.to/renegadecoder94/fizz-buzz-in-every-language-7o3
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

I noticed some folks on here were sharing some coding challenges, and I thought it might be fun to share some of my own (and shamelessly promote my Sample Programs project in the process).

The Challenge

Fizz Buzz is that notorious interview question almost everyone in the industry knows. Ironically, I don't know of anyone who has every been asked it. Regardless, it's a fun problem to tackle because it involves a little bit of everything: loops, conditions, math, etc. And, there are countless ways to solve it.

For the purposes of this challenge, here are the rules:

Write a program that prints the numbers 1 to 100. However, for multiples of three, print “Fizz” instead of the number. Meanwhile, for multiples of five, print “Buzz” instead of the number. For numbers which are multiples of both three and five, print “FizzBuzz”

Here's a segment of the output:

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
Enter fullscreen modeExit fullscreen mode

If you're feeling festive, you can swap the terms for whatever you like (i.e. EasterEgg, AprilShowers, etc.). In any case, the solution should be executable in any language of your choice. The more obscure the language, the better!

The Solution

I'll kick off the challenge with my favorite solution to the problem in Java:

public class FizzBuzz {
  public static void main(String[] args) {
    for (int i = 1; i < 101; i++) {
      String output = "";
      if (i % 3 == 0) {
        output += "Fizz";
      }
      if (i % 5 == 0) {
        output += "Buzz";
      }
      if (output.isEmpty()) {
        output += i;
      }
      System.out.println(output);
    }
  }
}
Enter fullscreen modeExit fullscreen mode

If you're curious how this solution works, Stuart Irwin wrote an excellent article about it. Along with this solution, I've been collecting several others in a repo called Sample Programs. After you drop your solution below, you should see if its missing from the collection. We'd love your contribution!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK