FizzBuzz

From Rosetta Code
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]

ActionScript

The ActionScript solution works just like the JavaScript solution (they share the ECMAScript specification). The difference is that ActionScript has the trace command to write out to a console.

<lang actionscript> for (var i:int = 1; i <= 100; i++) {

 if (i % 15 == 0)
   trace('FizzBuzz');
 else if (i % 5 == 0)
   trace('Buzz');
 else if (i % 3 == 0)
   trace('Fizz');
 else
   trace(i);

} </lang>


8086 Assembly

When assembly programs that do output a number on the screen are programmable in two ways: calculating the number in binary to convert it next in ASCII for output, or keeping the number in Binary Coded Decimal (BCD) notation to speed up the output to the screen, because no binary to decimal conversion needs to be applied. The first approach is the most useful because the binary number is immediately recognizable to the computer, but, in a problem where the calculations are very few and simple and the final result is mainly text on the screen, using binary numbers would speed up calculations, but will greatly slow down the output.

The BCD used is based on the ASCII text encoding: zero is the hexadecimal byte 30, and nine is the hexadecimal byte 39. The BCD number is kept in the DX register, the most significant digit in DH and the less significant digit in DL. See the comments for further explaining of the program's structure, wich is meant for speed and compactness rather than modularity: there are no subroutines reusable in another program without being edited.

This program is 102 bytes big when assembled. The program is written to be run in an IBM PC because the 8086 processor alone does not provide circuitry for any kind of direct screen output. At least, I should point out that this program is a little bugged: the biggest number representable with the BCD system chosen is 99, but the last number displayed is 100, wich would be written as :0 because the program does provide overflow detecting only for the units, not for tens (39 hex + 1 is 3A, that is the colon symbol in ASCII). However, this bug is hidden by the fact that the number 100 is a multiple of five, so the number is never displayed, because it is replaced by the string "buzz". <lang asm>  ; Init the registers mov dx,03030h  ; For easier printing, the number is

                   ;kept in Binary Coded Decimal, in

                   ;the DX register.

mov ah,0Eh  ; 0Eh is the IBM PC interrupt 10h

                   ;function that does write text on
                   ;the screen in teletype mode.

mov bl,100d  ; BL is the counter (100 numbers). xor cx,cx  ; CX is a counter that will be used

                   ;for screen printing.

xor bh,bh  ; BH is the counter for counting

                   ;multiples of three.

writeloop:  ; Increment the BCD number in DX. inc dl  ; Increment the low digit cmp dl,3Ah  ; If it does not overflow nine, jnz writeloop1 ;continue with the program, mov dl,30h ;otherwise reset it to zero and inc dh ;increment the high digit writeloop1: inc bh  ; Increment the BH counter. cmp bh,03h  ; If it reached three, we did

                   ;increment the number three times
                   ;from the last time the number was
                   ;a multiple of three, so the number
                   ;is now a multiple of three now,

jz writefizz ;then we need to write "fizz" on the

                   ;screen.

cmp dl,30h  ; The number isn't a multiple of jz writebuzz ;three, so we check if it's a cmp dl,35h ;multiple of five. If it is, we jz writebuzz ;need to write "buzz". The program

                   ;checks if the last digit is zero or
                   ;five.

mov al,dh  ; If we're here, there's no need to int 10h ;write neither "fizz" nor "buzz", so mov al,dl ;the program writes the BCD number int 10h ;in DX writespace: mov al,020h ;and a white space. int 10h dec bl  ; Loop if we didn't process 100 jnz writeloop ;numbers.

programend:  ; When we did reach 100 numbers, cli ;the program flow falls here, where hlt ;interrupts are cleared and the jmp programend ;program is stopped.

writefizz:  ; There's need to write "fizz": mov si,offset fizz  ; SI points to the "fizz" string, call write ;that is written on the screen. xor bh,bh  ; BH, the counter for computing the

                   ;multiples of three, is cleared.

cmp dl,30h  ; We did write "fizz", but, if the jz writebuzz ;number is a multiple of five, we cmp dl,35h ;could need to write "buzz" also: jnz writespace ;check if the number is multiple of

                   ;five. If not, write a space and
                   ;return to the main loop.

writebuzz:  ; (The above code falls here if

                   ;the last digit is five, otherwise
                   ;it jumps)

mov si,offset buzz ;SI points to the "buzz" string, call write ;that is written on the screen. jmp writespace  ; Write a space to return to the main

                   ;loop.

write:  ; Write subroutine: mov cl,04h  ; Set CX to the lenght of the string:

                   ;both strings are 4 bytes long.

write1: mov al,[si]  ; Load the character to write in AL. inc si  ; Increment the counter SI. int 10h  ; Call interrupt 10h, function 0Eh to

                   ;write the character and advance the
                   ;text cursor (teletype mode)

loop write1  ; Decrement CX: if CX is not zero, do ret ;loop, otherwise return from

                   ;subroutine.

fizz: ;The "fizz" string. db "fizz"

buzz: ;The "buzz" string. db "buzz"</lang>

Ada

<lang 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;</lang>

ALGOL 68

<lang algol68>main:(

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

)</lang> or simply: <lang algol68>FOR i TO 100 DO print(((i%*15=0|"FizzBuzz"|:i%*3=0|"Fizz"|:i%*5=0|"Buzz"|i),new line)) OD</lang>

APL

<lang apl>⎕IO←0 (L,'Fizz' 'Buzz' 'FizzBuzz')[¯1+(L×W=0)+W←(100×~0=W)+W←⊃+/1 2×0=3 5|⊂L←1+⍳100]</lang>

AutoHotkey

Search autohotkey.com: [3]
<lang AutoHotkey>Loop, 100 {

 If (Mod(A_Index, 15) = 0)
   output .= "FizzBuzz`n"
 Else If (Mod(A_Index, 3) = 0)
   output .= "Fizz`n"
 Else If (Mod(A_Index, 5) = 0)
   output .= "Buzz`n"
 Else
   output .= A_Index "`n"

} FileDelete, output.txt FileAppend, %output%, output.txt Run, cmd /k type output.txt</lang>

A short example with cascading ternary operators and graphical output. Press Esc to close the window. <lang AutoHotkey>Gui, Add, Edit, r20 Gui,Show Loop, 100

 Send, % (!Mod(A_Index, 15) ? "FizzBuzz" : !Mod(A_Index, 3) ? "Fizz" : !Mod(A_Index, 5) ? "Buzz" : A_Index) "`n"

Return Esc:: ExitApp</lang>

AWK

<lang AWK>BEGIN {

  for (NUM=1; NUM<=100; NUM++)
      if (NUM % 15 == 0)
          {print "FizzBuzz"}
      else if (NUM % 3 == 0)
          {print "Fizz"}
      else if (NUM % 5 == 0)
          {print "Buzz"}
      else
          {print NUM}

}</lang>

BASIC

Works with: QuickBasic version 4.5

If/else ladder approach

<lang qbasic>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</lang>

Concatenation approach

<lang qbasic>FOR A = 1 TO 100

  OUT$ = ""
  IF A MOD 3 = 0 THEN 
     OUT$ = "Fizz"
  END IF
  IF A MOD 5 = 0 THEN
     OUT$ = OUT$ + "Buzz"
  END IF
  
  IF OUT$ = "" THEN
     OUT$ = STR$(A)
  END IF
  PRINT OUT$

NEXT A</lang>

See also: RapidQ

Befunge

(befunge 93)

<lang befunge>55*4*v _ v v <>:1-:^

   |:<$      <    ,*48 <                                                       
   @>0"zzif">:#,_$      v                                                      

>:3%!| >0"zzub">:#,_$^

    >:5%!|                                                                     

v "buzz"0<>:. ^

        |!%5:           <                                                      

>:#,_ $> ^</lang>

C

<lang 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;

}</lang>

C++

<lang cpp>#include <iostream>

using namespace std; int main () {

      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;
      }
      return 0;

}</lang>

Alternate version not using modulo 15: <lang cpp>#include <iostream> using namespace std;

int main() {

 for (int i = 0; i <= 100; ++i)
 {
   bool fizz = (i % 3) == 0;
   bool buzz = (i % 5) == 0;
   if (fizz)
     cout << "Fizz";
   if (buzz)
     cout << "Buzz";
   if (!fizz && !buzz)
     cout << i;
   cout << endl;
 }

}</lang>

Version computing FizzBuzz at compile time with metaprogramming: <lang cpp>#include <iostream>

template <int n, int m3, int m5> struct fizzbuzz : fizzbuzz<n-1, (n-1)%3, (n-1)%5> {

 fizzbuzz() 
 { std::cout << n << std::endl; }

};

template <int n> struct fizzbuzz<n, 0, 0> : fizzbuzz<n-1, (n-1)%3, (n-1)%5> {

 fizzbuzz() 
 { std::cout << "FizzBuzz" << std::endl; }

};

template <int n, int p> struct fizzbuzz<n, 0, p> : fizzbuzz<n-1, (n-1)%3, (n-1)%5> {

 fizzbuzz() 
 { std::cout << "Fizz" << std::endl; }

};

template <int n, int p> struct fizzbuzz<n, p, 0> : fizzbuzz<n-1, (n-1)%3, (n-1)%5> {

 fizzbuzz() 
 { std::cout << "Buzz" << std::endl; }

};

template <> struct fizzbuzz<0,0,0> {

 fizzbuzz() 
 { std::cout << 0 << std::endl; }

};

template <int n> struct fb_run {

 fizzbuzz<n, n%3, n%5> fb;

};

int main() {

 fb_run<100> fb;

}</lang>

C#

<lang csharp>using System;

namespace RosettaCode.FizzBuzz {

   class Program
   {
       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 (String.IsNullOrEmpty(output)) output = i.ToString();
               Console.WriteLine(output);
           }
       }
   }

}</lang>

Clojure

<lang lisp>(map (fn [x] (cond (zero? (mod x 15)) "FizzBuzz"

                  (zero? (mod x 5)) "Buzz"
                  (zero? (mod x 3)) "Fizz"

:else x))

    (range 1 101))</lang>

<lang lisp>(def fizzbuzz (lazy-seq (map

 #(cond (zero? (mod % 15)) "FizzBuzz"
        (zero? (mod % 5)) "Buzz"
        (zero? (mod % 3)) "Fizz"
              :else %)
 (iterate inc 1))))</lang>

Common Lisp

<lang 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)))))</lang>

D

<lang 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") ;

}</lang>

E

<lang e>for i in 1..100 {

  println(switch ([i % 3, i % 5]) {
    match [==0, ==0] { "FizzBuzz" }
    match [==0, _  ] { "Fizz" }
    match [_,   ==0] { "Buzz" }
    match _          { i }
  })
}</lang>

Erlang

<lang erlang>fizzbuzz() ->

   F = fun(N) when N rem 15 == 0 -> "FizzBuzz";
          (N) when N rem 3 == 0  -> "Fizz";
          (N) when N rem 5 == 0  -> "Buzz";
          (N) -> integer_to_list(N)
       end,
   [F(N)++"\n" || N <- lists:seq(1,100)].</lang>

Factor

<lang factor>USING: math kernel io math.ranges ; IN: fizzbuzz

divides? ( m n -- ? ) mod 0 = ;
fizz ( n -- str ) 3 divides? "Fizz" "" ? ;
buzz ( n -- str ) 5 divides? "Buzz" "" ? ;
fizzbuzz ( n -- str ) dup [ fizz ] [ buzz ] bi append [ number>string ] [ nip ] if-empty ;
main ( -- ) 100 [1,b] [ fizzbuzz print ] each ;

MAIN: main</lang>

F#

<lang fsharp>

  1. light

[1..100] |> List.map (fun x ->

           match x with 
           | _ when x % 15 = 0 ->"fizzbuzz"
           | _ when x % 5 = 0 -> "buzz"
           | _ when x % 3 = 0 -> "fizz"
           | _ ->  x.ToString())

|> List.iter (fun x -> printfn "%s" x) </lang>

FALSE

<lang false>[\$@$@\/*=]d: [1\$3d;!["Fizz"\%0\]?$5d;!["Buzz"\%0\]?\[$.]?" "]f: 0[$100<][1+f;!]#%</lang>

Forth

table-driven

<lang forth>: 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 , ' . ,    ' . ,</lang>

or the classic approach

<lang forth>: .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</lang>

Fortran

In ANSI FORTRAN 66 or later use structured IF-THEN-ELSE (example uses some ISO Fortran 90 features): <lang fortran>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</lang>

In ISO Fortran 90 or later use SELECT-CASE statement: <lang fortran>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</lang>

Groovy

<lang groovy>for (i in 1..100) {

 println "${i%3?:'Fizz'}${i%5?:'Buzz'}" ?: i

}</lang>

Haskell

Variant directly implementing the specification:

<lang haskell>output x | x3 && x5 = "FizzBuzz"

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

main = mapM_ (putStrLn . output) [1..100] </lang>

Alternate implementation using lazy infinite lists and avoiding use of "mod":

<lang haskell> main = mapM_ putStrLn $ take 100 fizzbuzz

fizzbuzz = zipWith (\x y -> if null y then show x else y) [1..] fbs

fbs = zipWith (++) (cycle ["","","Fizz"]) (cycle ["","","","","Buzz"]) </lang>

Io

<lang io>for(a,1,100,

  if(a % 5 == 0) then(
     "FizzBuzz" println
  ) elseif(a % 3 == 0) then(
     "Fizz" println
  ) elseif(a % 5 == 0) then(
     "Buzz" println
  ) else (
     a println
  )

)</lang>

Iptscrae

Written in Iptscrae, the scripting language for The Palace chat software. <lang iptscrae>

FizzBuzz in Iptscrae

1 a = {

  "" b =
  { "fizz" b &= } a 3 % 0 == IF
  { "buzz" b &= } a 5 % 0 == IF
  { a ITOA LOGMSG } { b LOGMSG } b STRLEN 0 == IFELSE
  a ++

} { a 100 <= } WHILE </lang>

J

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

Solution 1 <lang j>Fizz=: 'Fizz' #~ 0 = 3&| Buzz=: 'Buzz' #~ 0 = 5&| FizzBuzz=: ": [^:( -: ]) Fizz,Buzz

FizzBuzz"0 >: i.100</lang>

Java

If/else ladder

<lang java>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); } } } }</lang>

Concatenation

<lang java>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); } } }</lang>

Ternary operator

<lang java>public class FizzBuzz{ public static void main(String[] args){ for(int i= 1; i <= 100; i++){ System.out.println(i % 15 != 0 ? i % 5 != 0 ? i % 3 != 0 ? i : "Fizz" : "Buzz" : "FizzBuzz" ;); } } }</lang>

Recursive

<lang java>public String fizzBuzz(int n){

 String s = "";
 if (n == 0)
   return s;
 if((n % 5) == 0)
   s = "Buzz" + s;
 if((n % 3) == 0)
   s = "Fizz" + s;
 if (s.equals(""))
   s = n + "";   
 return fizzBuzz(n-1) +  s;

}</lang>

Alternative Recursive

<lang java>public String fizzBuzz(int n){

 return (n>0) ? fizzBuzz(n-1) + 
   (n % 15 != 0? n % 5 != 0? n % 3 != 0? (n+"") :"Fizz" : "Buzz" : "FizzBuzz") 
              : "";

}</lang>

JavaScript

Works with: NJS version 0.2.5

<lang javascript>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);
 }

}</lang>

Lua

If/else Ladder

<lang Lua>for i = 1, 100 do if i % 15 == 0 then print("FizzBuzz") elseif i % 3 == 0 then print("Fizz") elseif i % 5 == 0 then print("Buzz") else print(i) end end</lang>

Concatenation

<lang Lua>for i = 1, 100 do output = "" if i % 3 == 0 then output = output.."Fizz" end if i % 5 == 0 then output = output.."Buzz" end if(output == "") then output = output..i end print(output) end</lang>

M4

<lang M4>define(`for',

  `ifelse($#,0,``$0,
  `ifelse(eval($2<=$3),1,
  `pushdef(`$1',$2)$5`'popdef(`$1')$0(`$1',eval($2+$4),$3,$4,`$5')')')')

for(`x',1,100,1,

  `ifelse(eval(x%15==0),1,FizzBuzz,
  `ifelse(eval(x%3==0),1,Fizz,
  `ifelse(eval(x%5==0),1,Buzz,x)')')

')</lang>

Mathematica

<lang Mathematica>Do[Print[Which[Mod[i, 15] == 0, "FizzBuzz", Mod[i, 5] == 0, "Buzz", Mod[i, 3] == 0, "Fizz", True, i]], {i, 100}]</lang>

MAXScript

<lang 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)
   )

)</lang>

Metafont

<lang metafont>for i := 1 upto 100: message if i mod 15 = 0: "FizzBuzz" & elseif i mod 3 = 0: "Fizz" & elseif i mod 5 = 0: "Buzz" & else: decimal i & fi ""; endfor end</lang>

Modula-3

<lang modula3>MODULE Fizzbuzz EXPORTS Main;

IMPORT IO;

BEGIN

  FOR i := 1 TO 100 DO 
     IF i MOD 15 = 0 THEN 
        IO.Put("FizzBuzz\n");
     ELSIF i MOD 5 = 0 THEN
        IO.Put("Buzz\n");
     ELSIF i MOD 3 = 0 THEN 
        IO.Put("Fizz\n");
     ELSE 
        IO.PutInt(i);
        IO.Put("\n");
     END;
  END;

END Fizzbuzz.</lang>

Oberon-2

<lang oberon2>MODULE FizzBuzz;

  IMPORT Out;
  VAR i: INTEGER;

BEGIN

  FOR i := 1 TO 100 DO 
     IF i MOD 15 = 0 THEN 
        Out.String("FizzBuzz");
        Out.Ln;
     ELSIF i MOD 5 = 0 THEN
        Out.String("Buzz");
        Out.Ln;
     ELSIF i MOD 3 = 0 THEN 
        Out.String("Fizz");
        Out.Ln;
     ELSE 
        Out.Int(i,0);
        Out.Ln;
     END;
  END;

END FizzBuzz.</lang>

OCaml

<lang 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</lang>

Octave

<lang octave>for i = 1:100

 if ( mod(i,15) == 0 )
   disp("FizzBuzz");
 elseif ( mod(i, 3) == 0 )
   disp("Fizz")
 elseif ( mod(i, 5) == 0 )
   disp("Buzz")
 endif

endfor</lang>

Oz

<lang oz>declare

 proc {FizzBuzz X}
    X3 = X mod 3 == 0
    X5 = X mod 5 == 0
 in
    {Show
     if X3 andthen X5 then 'FizzBuzz'
     elseif X3 then 'Fizz'
     elseif X5 then 'Buzz'
     else X
     end
    }
 end

in

 {ForAll {List.number 1 100 1} FizzBuzz}</lang>

Perl

<lang 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";
   };

};</lang>

More concisely:

<lang perl>print 'Fizz'x!($_ % 3) . 'Buzz'x!($_ % 5) || $_, "\n" for 1 .. 100;</lang>

Perl 6

Works with: Rakudo version #22 "Thousand Oaks"

Most straightforwardly:

<lang perl6>for 1 .. 100 {

   when $_ !% 3 and $_ !% 5 { say 'FizzBuzz'; }
   when $_ !% 3             { say 'Fizz'; }
   when $_ !% 5             { say 'Buzz'; }
   default                  { .say; }

}</lang>

Most concisely:

<lang perl6>say 'Fizz' x $_ !% 3 ~ 'Buzz' x $_ !% 5 || $_ for 1 .. 100;</lang>

And here's an implementation that never checks for divisibility:

<lang perl6>for

 ( xx 2, 'Fizz') xx 34 Z
 ( xx 4, 'Buzz') xx 20 Z
 1 .. 100
 -> $f, $b, $n {
   say $f ~ $b || $n;

}</lang>

PHP

if/else ladder approach

<lang php><?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";

} ></lang>

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.

<lang php><?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";

} ?></lang>

Pike

<lang pike>int main(){

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

}</lang>

Pop11

<lang 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;</lang>

PostScript

<lang postscript>1 1 100 { /c false def dup 3 mod 0 eq { (Fizz) print /c true def } if dup 5 mod 0 eq { (Buzz) print /c true def } if

   c {pop}{(   ) cvs print} ifelse
   (\n) print

} for</lang> or... <lang postscript>/fizzdict 100 dict def fizzdict begin /notmod{ ( ) cvs } def /mod15 { dup 15 mod 0 eq { (FizzBuzz)def }{pop}ifelse} def /mod3 { dup 3 mod 0 eq {(Fizz)def}{pop}ifelse} def /mod5 { dup 5 mod 0 eq {(Buzz)def}{pop}ifelse} def 1 1 100 { mod3 } for 1 1 100 { mod5 } for 1 1 100 { mod15} for 1 1 100 { dup currentdict exch known { currentdict exch get}{notmod} ifelse print (\n) print} for end</lang>

PowerShell

Straightforward, looping

<lang powershell>for ($i = 1; $i -le 100; $i++) {

   if ($i % 15 -eq 0) {
       "FizzBuzz"
   } elseif ($i % 5 -eq 0) {
       "Buzz"
   } elseif ($i % 3 -eq 0) {
       "Fizz"
   } else {
       $i
   }

}</lang>

Straightforward, Pipeline, Switch

<lang powershell>1..100 | ForEach-Object {

   switch ($_) {
       { $_ % 15 -eq 0 } { "FizzBuzz" }
       { $_ % 5 -eq 0 }  { "Buzz" }
       { $_ % 3 -eq 0 }  { "Fizz" }
       default           { $_ }
   }

}</lang>

Concatenation

Translation of: C#

<lang powershell>1..100 | ForEach-Object {

   $s = 
   if ($_ % 3 -eq 0) { $s += "Fizz" }
   if ($_ % 5 -eq 0) { $s += "Buzz" }
   if (!$s) { $s = $_ }
   $s

}</lang>

Prolog

Works with: SWI Prolog version 4.8.0

Maybe not the most conventional way to write this in Prolog. The fizzbuzz predicate uses a higher-order predicate and print_item uses the if-then-else construction.

<lang prolog>fizzbuzz :-

       foreach(between(1, 100, X), print_item(X)).

print_item(X) :-

       (  X mod 15 =:= 0
       -> print('FizzBuzz')
       ;  X mod 3 =:= 0
       -> print('Fizz')
       ;  X mod 5 =:= 0
       -> print('Buzz')
       ;  print(X)
       ),
       nl.</lang>

Python

<lang 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</lang>

And a shorter, but less clear version, using a list comprehension and logical expressions: <lang python>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</lang>

Without modulus

I came across this crazy version[4] without using the modulus operator: <lang python>messages = [None, "Fizz", "Buzz", "FizzBuzz"] acc = 810092048 for i in xrange(1, 101):

   c = acc & 3
   print messages[c] if c else i
   acc = acc >> 2 | c << 28</lang>

R

<lang R>x <- 1:100 xx <- as.character(x) xx[x%%3==0] <- "Fizz" xx[x%%5==0] <- "Buzz" xx[x%%15==0] <- "FizzBuzz" xx</lang>

RapidQ

The BASIC solutions work with RapidQ, too.
However, here is a bit more esoteric solution using the IIF() function. <lang rapidq>FOR i=1 TO 100

   t$ = IIF(i MOD 3 = 0, "Fizz", "") + IIF(i MOD 5 = 0, "Buzz", "")
   PRINT IIF(LEN(t$), t$, i)

NEXT i</lang>

Raven

<lang 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</lang>

REBOL

<lang REBOL>REBOL [ Title: "FizzBuzz" Author: oofoe Date: 2009-12-10 URL: http://rosettacode.org/wiki/FizzBuzz ]

Concatenative. Note use of 'case/all' construct to evaluate all
conditions. I use 'copy' to allocate a new string each time through
the loop -- otherwise 'x' would get very long...

repeat i 100 [ x: copy "" case/all [ 0 = mod i 3 [append x "Fizz"] 0 = mod i 5 [append x "Buzz"] "" = x [x: mold i] ] print x ]

The following is presented as a curiosity only, not as an example of
good coding practice

m: func [i d] [0 = mod i d] spick: func [t x y][either any [not t "" = t][y][x]] zz: func [i] [rejoin [spick m i 3 "Fizz" "" spick m i 5 "Buzz" ""]] repeat i 100 [print spick z: zz i z i]</lang>

Ruby

<lang 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</lang>

Scala

<lang scala>(1 to 100) foreach {

   case x if (x % 15 == 0) => println("FizzBuzz")
   case x if (x % 3 == 0) => println("Fizz")
   case x if (x % 5 == 0) => println("Buzz")
   case x => println(x)                          

}</lang> <lang scala>(1 to 100) map ( x => (x % 3, x % 5) match{

   case (0,0) => "FizzBuzz"
   case (0,_) => "Fizz"
   case (_,0) => "Buzz"
   case _ => x

}) foreach println</lang>

Scheme

<lang scheme>(do ((i 1 (+ i 1)))

   ((> i 100))
   (display
     (cond ((= 0 (modulo i 15)) "FizzBuzz")
           ((= 0 (modulo i 3))  "Fizz")
           ((= 0 (modulo i 5))  "Buzz")
           (else                i)))
   (newline))</lang>

Seed7

<lang 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;</lang>

Slate

<lang slate>n@(Integer traits) fizzbuzz [| output |

 output: ((n \\ 3) isZero ifTrue: ['Fizz'] ifFalse: []) ; ((n \\ 5) isZero ifTrue: ['Buzz'] ifFalse: []).
 output isEmpty ifTrue: [n printString] ifFalse: [output]

]. 1 to: 100 do: [| :i | inform: i fizzbuzz]</lang>

Smalltalk

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

<lang smalltalk>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 ]</lang>

A Squeak/Pharo example using the Transcript window: <lang smalltalk>(1 to: 100) do: [:n | ((n \\ 3)*(n \\ 5)) isZero

                       ifFalse: [Transcript show: n].

(n \\ 3) isZero ifTrue: [Transcript show: 'Fizz']. (n \\ 5) isZero ifTrue: [Transcript show: 'Buzz']. Transcript cr.]</lang>

The Squeak/Pharo examples below present possibilities using the powerful classes available. In this example, the dictionary can have as keys pairs of booleans and in the interaction the several boolean patterns select the string to be printed or if the pattern is not found the number itself is printed.

<lang smalltalk>fizzbuzz := Dictionary with: #(true true)->'FizzBuzz'

                      with: #(true false)->'Fizz' 
                      with: #(false true)->'Buzz'.

1 to: 100 do: [ :i | Transcript show:

              (fizzbuzz at: {i isDivisibleBy: 3. i isDivisibleBy: 5} 

ifAbsent: [ i ]); cr]</lang>

Smalltalk does not have a case-select construct, but a similar effect can be attained using a collection and the #includes: method:

<lang smalltalk>1 to: 100 do: [:n | |r| r := n rem: 15. Transcript show: (r isZero ifTrue:['fizzbuzz'] ifFalse: [(#(3 6 9 12) includes: r) ifTrue:['fizz'] ifFalse:[((#(5 10) includes: r)) ifTrue:['buzz'] ifFalse:[n]]]); cr].</lang>

If the construction of the whole collection is done beforehand, Smalltalk provides a straightforward way of doing because collections can be heterogeneous (may contain any object):

<lang smalltalk>fbz := (1 to: 100) asOrderedCollection.

3 to: 100 by:  3 do: [:i | fbz at: i put: 'Fizz'].
5 to: 100 by:  5 do: [:i | fbz at: i put: 'Buzz'].

15 to: 100 by: 15 do: [:i | fbz at: i put: 'FizzBuzz']. fbz do: [:i | Transcript show: i; cr].</lang>

The approach building a dynamic string can be done as well:

<lang smalltalk>1 to: 100 do: [:i | |fb s| fb := {i isDivisibleBy: 3. i isDivisibleBy: 5. nil}. fb at: 3 put: (fb first | fb second) not. s := '<1?Fizz:><2?Buzz:><3?{1}:>' format: {i printString}. Transcript show: (s expandMacrosWithArguments: fb); cr].</lang>

SNUSP

<lang snusp> / 'B' @=@@=@@++++#

      // /             'u' @@@@@=@+++++#
     // // /           'z' @=@@@@+@++++#
    // // // /         'i' @@@@@@=+++++#
   // // // // /       'F' @@@=@@+++++#
  // // // // // /      LF  ++++++++++#
 // // // // // // /   100 @@@=@@@=++++#

$@/>@/>@/>@/>@/>@/>@/\ 0 / / ! /======= Fizz <<<.<.<..>>># / | \ \?!#->+ @\.>?!#->+ @\.>?!#->+@/.>\ | /  !  !  ! / | \?!#->+ @\.>?!#->+@\ .>?!#->+@/.>\ | /  ! \!===\!  ! / | \?!#->+ @\.>?!#->+ @\.>?!#->+@/.>\ | /  !  ! |  ! / | \?!#->+@\ .>?!#->+ @\.>?!#->+@/.>\ | / \!==========!===\!  ! / | \?!#->+ @\.>?!#->+ @\.>?!#->+@/>>@\.>/

        !          |   |         |
        /==========/   \========!\=== Buzz <<<<<<<.>.>..>>>#
        |
        \!/=dup==?\>>@\<!/back?\<<<#
          \<<+>+>-/   |  \>+<- /
                      |

/======================/ | | /recurse\ #/?\ zero \print=!\@\>?!\@/<@\.!\-/

         |   \=/  \=itoa=@@@+@+++++#
         !     /+ !/+ !/+ !/+   \    mod10
         /<+> -\!?-\!?-\!?-\!?-\!
         \?!\-?!\-?!\-?!\-?!\-?/\    div10
            #  +/! +/! +/! +/! +/</lang>

Standard ML

<lang sml>fun output x =

 case (x mod 3 = 0, x mod 5 = 0) of
   (true , true ) => "FizzBuzz"
 | (true , false) => "Fizz"
 | (false, true ) => "Buzz"
 | (false, false) => Int.toString x

val () = let

 fun aux i = if i <= 100 then (print (output i ^ "\n");
                           aux (i+1))
                     else ()

in

 aux 1

end</lang>

Tcl

<lang tcl>proc fizzbuzz {n {m1 3} {m2 5}} {

   for {set i 1} {$i <= $n} {incr i} {
       set ans ""
       if {$i % $m1 == 0} {append ans Fizz}
       if {$i % $m2 == 0} {append ans Buzz}
       puts [expr {$ans eq "" ? $i : $ans}]
   }

} fizzbuzz 100</lang>

UNIX Shell

<lang bash>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</lang>

A more portable version:

<lang bash>NUM=1 until (($NUM==101)) ; do

  if (($NUM % 15 == 0)) ; then
      echo FizzBuzz
  elif (($NUM % 3 == 0)) ; then
      echo Fizz
  elif (($NUM % 5 == 0)) ; then
      echo Buzz
  else 
      echo "$NUM"
  fi
  ((NUM=$NUM+1))

done</lang>

Ursala

<lang Ursala>#import std

  1. import nat

fizzbuzz = ^T(&&'Fizz'! not remainder\3,&&'Buzz'! not remainder\5)|| ~&h+ %nP

  1. show+

main = fizzbuzz*t iota 101</lang>

V

<lang v>[fizzbuzz

   1 [>=] [
    [[15 % zero?] ['fizzbuzz' puts]
     [5 % zero?]  ['buzz' puts]
     [3 % zero?]  ['fizz' puts]
     [true] [dup puts]
   ] when succ
 ] while].
|100 fizzbuzz</lang>

Second try

(a compiler for fizzbuzz)

define a command that will generate a sequence <lang v>[seq [] swap dup [zero? not] [rolldown [dup] dip cons rollup pred] while pop pop].</lang>

create a quote that will return a quote that returns a quote if its argument is an integer (A HOF) <lang v>[check [N X F : [[integer?] [[X % zero?] [N F cons] if] if]] view].</lang>

Create a quote that will make sure that the above quote is applied correctly if given (Number Function) as arguments. <lang v>[func [[N F] : [dup N F check i] ] view map].</lang>

And apply it <lang v>100 seq [

       [15 [pop 'fizzbuzz' puts]]
       [5  [pop 'buzz' puts]]
       [3  [pop 'fizz' puts]] 
       [1  [puts]]] [func dup] step
       [i true] map pop</lang>

the first one is much better :)

Visual Basic .NET

Platform: .NET

Works with: Visual Basic .NET version 9.0+

<lang vbnet>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</lang>