FizzBuzz

From Rosetta Code
Revision as of 02:24, 24 July 2008 by 124.171.56.86 (talk) (add PostScript version)
FizzBuzz is a programming puzzle. It lays out a problem which Rosetta Code users are encouraged to solve, using languages and techniques they know. Multiple approaches are not discouraged, so long as the puzzle guidelines are followed. For other Puzzles, see Category:Puzzles.

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". [1]

FizzBuzz was presented as the lowest level of comprehension required to illustrate adequacy. [2]


Ada

with Ada.Text_Io; use Ada.Text_Io;

procedure Fizzbuzz is
begin
   for I in 1..100 loop
      if I mod 15 = 0 then
         Put_Line("FizzBuzz");
      elsif I mod 5 = 0 then
         Put_Line("Buzz");
      elsif I mod 3 = 0 then
         Put_Line("Fizz");
      else
         Put_Line(Integer'Image(I));
      end if;
   end loop;
end Fizzbuzz;

ALGOL 68

main: (
  FOR i TO 100 DO
    IF i %* 15 = 0 THEN
      printf ($"FizzBuzz"l$)
    ELIF i %* 3 = 0 THEN
      printf ($"Fizz"l$)
    ELIF i %* 5 = 0 THEN
      printf ($"Buzz"l$)
    ELSE
      printf (($gl$, i))
    FI
  OD
)

BASIC

Works with: QuickBasic version 4.5

If/else ladder approach

FOR A = 1 TO 100
   IF A MOD 15 = 0 THEN
      PRINT "FizzBuzz"
   ELSE IF A MOD 3 = 0 THEN
      PRINT "Fizz"
   ELSE IF A MOD 5 = 0 THEN
      PRINT "Buzz"
   ELSE
      PRINT A
   END IF
NEXT A

Concatenation approach

FOR A = 1 TO 100
   OUT$ = ""
   IF A MOD 3 = 0 THEN 
      OUT$ = OUT& + "Fizz"
   END IF

   IF A MOD 5 = 0 THEN
      OUT$ = OUT$ + "Buzz"
   END IF
   
   IF OUT$ = "" THEN
      OUT$ = OUT$ + A
   END IF

   PRINT OUT$
NEXT A

C

#include<stdio.h>

int main (void)
{
    int i;
    for (i = 1; i <= 100; i++)
    {
        if (!(i % 15))
            printf ("FizzBuzz\n");
        else if (!(i % 3))
            printf ("Fizz\n");
        else if (!(i % 5))
            printf ("Buzz\n");
        else
            printf ("%d\n", i);
    }
    return 0;
}

C++

#include <istream.h>

using namespace std;
int main () {

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

Common Lisp

(defun fizzbuzz ()
  (loop for x from 1 to 100 do
    (print (cond ((zerop (mod x 15)) "FizzBuzz")
                 ((zerop (mod x 3))  "Fizz")
                 ((zerop (mod x 5))  "Buzz")
                 (t                  x)))))
(defun fizzbuzz ()
  (loop for x from 1 to 100 do
    (format t "~&~{~A~}"
      (or (append (when (zerop (mod x 3)) '("Fizz"))
                  (when (zerop (mod x 5)) '("Buzz")))
          (list x)))))

D

module fizzbuzz;
import std.stdio;
import std.string ;

// if-else
void fizzBuzz(int n) {
  for(int i = 1 ; i <= n; i++)
    if (!(i%15))
      writef("FizzBuzz") ;
    else if (!(i%3))
      writef("Fizz") ;
    else if (!(i%5))
      writef("Buzz") ;
    else
      writef(i) ;
  writefln() ;
}

// use switch case
void fizzBuzz_s(int n) {
  for(int i = 1 ; i <= n; i++)
    switch(i%15) {
      case 0:
        writef("FizzBuzz") ; break ;        
      case 3,6,9,12:
        writef("Fizz") ; break ;
      case 5,10:
        writef("Buzz") ; break ;
      default:
        writef(i) ;
    }
  writefln() ;
}

// recursive with concatenation
string fizzBuzz_r(int n){
  string s = "" ;
  if (n == 0)
    return s ;
  if(!(n % 5))
    s = "Buzz"~ s ;
  if(!(n % 3))
    s = "Fizz" ~ s ;
  if (s == "")
    s = toString(n) ;   
  return fizzBuzz_r(n-1) ~  s ;
}

// alternative recursive
string fizzBuzz_r2(int n){
  return (n>0) ? fizzBuzz_r2(n-1) ~ 
    (n % 15 ? n % 5 ? n % 3 ? toString(n) :"Fizz" : "Buzz" : "FizzBuzz") 
               : "";
}

void main() {
  fizzBuzz(100) ;
  fizzBuzz_s(100) ;
  writefln(fizzBuzz_r(100)) ;
  writefln(fizzBuzz_r2(100)) ;
  for(int i = 1 ; i <= 100;i++)
  writef("%s", i % 15 ? i % 5 ? i % 3 ? toString(i) :"Fizz" : "Buzz" : "FizzBuzz") ;
}

E

for i in 1..100 {
  println(switch ([i % 3, i % 5]) {
    match [==0, ==0] { "FizzBuzz" }
    match [==0, _  ] { "Fizz" }
    match [_,   ==0] { "Buzz" }
    match _          { i }
  })
}

Factor

IN: fizzbuzz
USING: math kernel io ;
: divides? ( m n -- ? ) mod 0 = ;
: fizz ( n -- str ) 3 divides? [ "Fizz" ] [ "" ] if ;
: buzz ( n -- str ) 5 divides? [ "Buzz" ] [ "" ] if ;
: fizzbuzz ( n -- str ) dup fizz over buzz append dup empty? [ nip ] [ drop number>string ] if ;
: main ( -- ) 100 [ 1+ fizzbuzz print ] each ;
MAIN: main

Forth

table-driven

: fizz ( n -- ) drop ." Fizz" ;
: buzz ( n -- ) drop ." Buzz" ;
: fb   ( n -- ) drop ." FizzBuzz" ;
: vector create does> ( n -- )
  over 15 mod cells + @ execute ;
vector .fizzbuzz
  ' fb   , ' . ,    ' . ,
  ' fizz , ' . ,    ' buzz ,
  ' fizz , ' . ,    ' . ,
  ' fizz , ' buzz , ' . ,
  ' fizz , ' . ,    ' . ,

or the classic approach

: .fizzbuzz ( n -- )
  0 pad c!
  dup 3 mod 0= if s" Fizz" pad  place then
  dup 5 mod 0= if s" Buzz" pad +place then
  pad c@ if drop pad count type else . then ;

: zz ( n -- )
  1+ 1 do i .fizzbuzz cr loop ;
100 zz

Fortran

In ANSI FORTRAN 66 or later use structured IF-THEN-ELSE (example uses some ISO Fortran 90 features):

  program fizzbuzz_if
     integer :: i
     
     do i = 1, 100
        if     (mod(i,15) == 0) then; print *, 'FizzBuzz'
        else if (mod(i,3) == 0) then; print *, 'Fizz'
        else if (mod(i,5) == 0) then; print *, 'Buzz'
        else;                         print *, i
        end if
     end do
  end program fizzbuzz_if

In ISO Fortran 90 or later use SELECT-CASE statement:

  program fizzbuzz_select
     integer :: i
     
     do i = 1, 100
        select case (mod(i,15))
           case 0;        print *, 'FizzBuzz'
           case 3,6,9,12; print *, 'Fizz'
           case 5,10;     print *, 'Buzz'
           case default;  print *, i
        end select
     end do
  end program fizzbuzz_select

Groovy

for (i in 1..100) {
  println "${i%3?'':'Fizz'}${i%5?'':'Buzz'}" ?: i
}

Haskell

Variant directly implementing the specification:

output x | x3 && x5  =  "FizzBuzz"
         | x3        =  "Fizz"
         | x5        =  "Buzz"
         | otherwise = show x
         where 
           x3 = x `mod` 3 == 0 
           x5 = x `mod` 5 == 0 

answer = map output [1..100]

J

Solution 0

> }. (<'FizzBuzz') (I.0=15|n)} (<'Buzz') (I.0=5|n)} (<'Fizz') (I.0=3|n)} ":&.> n=: i.101

Solution 1

Fizz=: 'Fizz' #~ 0 = 3&|
Buzz=: 'Buzz' #~ 0 = 5&|
FizzBuzz=: ": [^:(''-:]) Fizz,Buzz

FizzBuzz"0 >: i.100

Java

If/else ladder approach

public class FizzBuzz{
	public static void main(String[] args){
		for(int i= 1; i <= 100; i++){
			if(i % 15 == 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);
			}
		}
	}
}

Concatenation approach

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

JavaScript

Works with: NJS version 0.2.5
for (var i = 1; i <= 100; i++) {
  if (i % 15 == 0) {
    print("FizzBuzz");
  } else if (i % 3 == 0) {
    print("Fizz");
  } else if (i % 5 == 0) {
    print("Buzz");
  } else {
    print(i);
  }
}

MAXScript

for i in 1 to 100 do
(
    case of
    (
        (mod i 15 == 0): (print "FizzBuzz")
        (mod i 5 == 0):  (print "Buzz")
        (mod i 3 == 0):  (print "Fizz")
        default:         (print i)
    )
)

OCaml

let output x =
  match x mod 3 = 0, x mod 5 = 0 with
    true,  true  -> "FizzBuzz"
  | true,  false -> "Fizz"
  | false, true  -> "Buzz"
  | false, false -> string_of_int x

let _ =
  for i = 1 to 100 do print_endline (output i) done

Perl

<perl>foreach (1 .. 100) {

   if (0 == $_ % 15) {
       print "FizzBuzz\n";
   } elsif (0 == $_ % 3) {
       print "Fizz\n";
   } elsif (0 == $_ % 5) {
       print "Buzz\n";
   } else {
       print "$_\n";
   };

};</perl>

More concisely:

<perl>sub f { $_[0] % $_[1] ?  : $_[2] } print f($_, 3, 'Fizz') . f($_, 5, 'Buzz') || $_, "\n"

   foreach 1 .. 100;</perl>

PHP

if/else ladder approach

<?php
for ($i = 1; $i <= 100; $i++)
{
    if (!($i % 15))
        echo "FizzBuzz\n";
    else if (!($i % 3))
        echo "Fizz\n";
    else if (!($i % 5))
        echo "Buzz\n";
    else
        echo "$i\n";
}
?>

concatenation approach

Uses PHP's concatenation operator (.=) to build the output string. The concatenation operator allows us to add data to the end of a string without overwriting the whole string. Since Buzz will always appear if our number is divisible by five, and Buzz is the second part of "FizzBuzz", we can simply append "Buzz" to our string.

In contrast to the if-else ladder, this method lets us skip the check to see if $i is divisible by both 3 and 5 (i.e. 15). However, we get the added complexity of needing to reset $str to an empty string (not necessary in some other languages), and we also need a separate if statement to check to see if our string is empty, so we know if $i was not divisible by 3 or 5.

<?php
for ( $i = 1; $i <= 100; ++$i )
{
     $str = "";

     if (!($i % 3 ) )
          $str .= "Fizz";

     if (!($i % 5 ) )
          $str .= "Buzz";

     if ( empty( $str ) )
          $str = $i;

     echo "$str\n";
}
?>

Pop11

lvars str;
for i from 1 to 100 do
  if i rem 15 = 0 then
    'FizzBuzz' -> str;
  elseif i rem 3 = 0 then
    'Fizz' -> str;
  elseif i rem 5 = 0 then
    'Buzz' -> str;
  else
    '' >< i -> str;
  endif;
  printf(str, '%s\n');
endfor;

PostScript

1 1 100 { 
	dup 3 mod 0 eq {(Fizz) print pop}{dup 5 mod 0 eq {(Buzz) print pop }{pop}ifelse} ifelse
} for

Python

for i in xrange(1, 101):
    if i % 15 == 0:
        print "FizzBuzz"
    elif i % 3 == 0:
        print "Fizz"
    elif i % 5 == 0:
        print "Buzz"
    else:
        print i

And a shorter version with less duplication:

for i in range(1, 101):
    words = [word for n, word in ((3, 'Fizz'), (5, 'Buzz')) if not i % n]
    print ''.join(words) or i

Raven

100 each 1 + as n
  ''
  n 3 mod 0 = if 'Fizz' cat
  n 5 mod 0 = if 'Buzz' cat
  dup empty if drop n
  say

Ruby

1.upto(100) do |n|
  print "Fizz" if a = (n % 3).zero?
  print "Buzz" if b = (n % 5).zero?
  print n unless (a || b)
  print "\n"
end

Seed7

$ include "seed7_05.s7i";

const proc: main is func
  local
    var integer: number is 0;
  begin
    for number range 1 to 100 do
      if number rem 15 = 0 then
        writeln("FizzBuzz");
      elsif number rem 5 = 0 then
        writeln("Buzz");
      elsif number rem 3 = 0 then
        writeln("Fizz");
      else
        writeln(number);
      end if;
    end for;
  end func;

Smalltalk

Since only GNU Smalltalk supports file-based programming, we'll be using its syntax.

Integer extend [
    fizzbuzz [
        | fb |
        fb := '%<Fizz|>1%<Buzz|>2' % {
            self \\ 3 == 0.  self \\ 5 == 0 }.
        ^fb isEmpty ifTrue: [ self ] ifFalse: [ fb ]
    ]
]
1 to: 100 do: [ :i | i fizzbuzz displayNl ]

Visual Basic .NET

Platform: .NET

Works with: Visual Basic .NET version 9.0+
   Sub Main()

       For i = 1 To 100
           If i Mod 15 = 0 Then
               Console.WriteLine("FizzBuzz")
           ElseIf i Mod 5 = 0 Then
               Console.WriteLine("Buzz")
           ElseIf i Mod 3 = 0 Then
               Console.WriteLine("Fizz")
           Else
               Console.WriteLine(i)
           End If
       Next

   End Sub

UNIX Shell

for n in `seq 1 100`; do
  if  [ $(($n % 15)) = 0 ]; then
    echo FizzBuzz
  elif [ $(($n % 3)) = 0 ]; then
    echo Fizz
  elif [ $(($n % 5)) = 0 ]; then
    echo Buzz
  else
    echo $n
  fi
done