# FizzBuzz

FizzBuzz
You are encouraged to solve this task according to the task description, using any language you may know.
Task

Write a program that prints the integers from   1   to   100   (inclusive).

But:

•   for multiples of three,   print   Fizz     (instead of the number)
•   for multiples of five,   print   Buzz     (instead of the number)
•   for multiples of both three and five,   print   FizzBuzz     (instead of the number)

The   FizzBuzz   problem was presented as the lowest level of comprehension required to illustrate adequacy.

Also see

## 11l

Translation of: Python3: Simple
L(i) 1..100   I i % 15 == 0      print(‘FizzBuzz’)   E I i % 3 == 0      print(‘Fizz’)   E I i % 5 == 0      print(‘Buzz’)   E      print(i)

## 8th

 with: n : num?  \ n f --   ) 	if drop else . then ; \ is m mod n 0? leave the result twice on the stack: div? \ m n -- f f	mod 0 = dup ; : fizz? \ n -- n f	dup 3 	div? if "Fizz" .  then ; : buzz? \ n f -- n f	over 5 	div? if "Buzz" .  then or ; \ print a message as appropriate for the given number:: fizzbuzz  \ n --	fizz? buzz? num? 	space ; \ iterate from 1 to 100:' fizzbuzz 1 100 loop cr bye

## AArch64 Assembly

Works with: as version Raspberry Pi 3B version Buster 64 bits
 /* ARM assembly AARCH64 Raspberry PI 3B *//*  program FizzBuzz64.s   */ /*******************************************//* Constantes file                         *//*******************************************//* for this file see task include a file in language AArch64 assembly*/.include "../includeConstantesARM64.inc" /*******************************************//* Initialized data                        *//*******************************************/.dataszMessFizz:        .asciz "Fizz\n"szMessBuzz:        .asciz "Buzz\n"szMessFizzBuzz:    .asciz "FizzBuzz\n"szMessNumber:      .asciz "Number : @ "szCarriageReturn:  .asciz "\n" /*******************************************//* UnInitialized data                      *//*******************************************/.bss sZoneConv:         .skip 24/*******************************************//*  code section                           *//*******************************************/.text.global main main:                           // entry of program     mov x10,3                   // divisor 3    mov x11,5                   // divisor 5    mov x12,15                  // divisor 15    mov x13,1                   // indice1:                              // loop begin    udiv x14,x13,x12            // multiple 15    msub x15,x14,x12,x13        // remainder    cbnz x15,2f                 // zero ?    mov x0,x13    ldr x1,qAdrszMessFizzBuzz    bl displayResult    b 4f2:                              // multiple 3    udiv x14,x13,x10    msub x15,x14,x10,x13        // remainder    cbnz x15,3f                 // zero ?    mov x0,x13    ldr x1,qAdrszMessFizz    bl displayResult    b 4f3:                               // multiple 5    udiv x14,x13,x11    msub x15,x14,x11,x13         // remainder     cbnz x15,4f                  // zero ?    mov x0,x13    ldr x1,qAdrszMessBuzz    bl displayResult4:    add x13,x13,1                // increment indice     cmp x13,100                  // maxi ?    ble 1b 100:                            // standard end of the program     mov x8,EXIT                 // request to exit program    svc 0                       // perform the system callqAdrszMessFizzBuzz:        .quad szMessFizzBuzzqAdrszMessFizz:            .quad szMessFizzqAdrszMessBuzz:            .quad szMessBuzz/******************************************************************//*     Display résult                                            */ /******************************************************************//* x0 contains the number*//* x1 contains display string address    */displayResult:    stp x2,lr,[sp,-16]!            // save  registers    mov x2,x1    ldr x1,qAdrsZoneConv           // conversion number    bl conversion10S               // decimal conversion    ldr x0,qAdrszMessNumber    ldr x1,qAdrsZoneConv    bl strInsertAtCharInc          // insert result at @ character    bl affichageMess               // display message final    mov x0,x2    bl affichageMess      ldp x2,lr,[sp],16              // restaur  2 registers    ret                            // return to address lr x30qAdrsZoneConv:        .quad sZoneConvqAdrszMessNumber:     .quad szMessNumber/********************************************************//*        File Include fonctions                        *//********************************************************//* for this file see task include a file in language AArch64 assembly */.include "../includeARM64.inc"

## ABAP

### Impure Functional 1

Works with: ABAP version 7.4 SP05 or Above only
DATA: tab TYPE TABLE OF string. tab = VALUE #(  FOR i = 1 WHILE i <= 100 (    COND string( LET r3 = i MOD 3                     r5 = i MOD 5 IN                 WHEN r3 = 0 AND r5 = 0 THEN |FIZZBUZZ|                 WHEN r3 = 0            THEN |FIZZ|                 WHEN r5 = 0            THEN |BUZZ|                 ELSE i ) ) ). cl_demo_output=>write( tab ).cl_demo_output=>display( ).

### Impure Functional 2

Works with: ABAP version 7.4 SP05 or Above only
cl_demo_output=>display( VALUE stringtab( FOR i = 1 WHILE i <= 100 ( COND #(  LET m3 = i MOD 3 m5 = i MOD 5 IN                                                                             WHEN m3 = 0 AND m5 = 0 THEN |FIZZBUZZ|                                                                             WHEN m3 = 0            THEN |FIZZ|                                                                             WHEN m5 = 0            THEN |BUZZ|                                                                             ELSE i ) ) ) ).

## ACL2

### Example2

Output via console, logfile and/or messagebox:

#include <Constants.au3> ; uncomment how you want to do the outputFunc Out($Msg) ConsoleWrite($Msg & @CRLF) ;~	FileWriteLine("FizzBuzz.Log", $Msg) ;~$Btn = MsgBox($MB_OKCANCEL +$MB_ICONINFORMATION, "FizzBuzz", $Msg);~ If$Btn > 1 Then Exit	; Pressing 'Cancel'-button aborts the programEndFunc   ;==>Out Out("# FizzBuzz:")For $i = 1 To 100 If Mod($i, 15) = 0 Then		Out("FizzBuzz")	ElseIf Mod($i, 5) = 0 Then Out("Buzz") ElseIf Mod($i, 3) = 0 Then		Out("Fizz")	Else		Out($i) EndIfNextOut("# Done.") ## Avail For each i from 1 to 100 do [ Print: if i mod 15 = 0 then ["FizzBuzz"] else if i mod 3 = 0 then ["Fizz"] else if i mod 5 = 0 then ["Buzz"] else [“i”] ++ "\n";]; ## AWK See FizzBuzz/AWK ## Axe For(I,1,100)!If I^3??I^5 Disp "FIZZBUZZ",iElse!If I^3 Disp "FIZZ",iElse!If I^5 Disp "BUZZ",iElse Disp I▶Dec,iEnd.Pause to allow the user to actually read the outputPause 1000End ## Babel main: { { iter 1 + dup 15 % { "FizzBuzz" << zap } { dup 3 % { "Fizz" << zap } { dup 5 % { "Buzz" << zap} { %d << } if } if } if "\n" << } 100 times } ## BaCon ## bash Any bash hacker would do this as a one liner at the shell, so... for n in {1..100}; do ((( n % 15 == 0 )) && echo 'FizzBuzz') || ((( n % 5 == 0 )) && echo 'Buzz') || ((( n % 3 == 0 )) && echo 'Fizz') || echo$n; done

For the sake of readability...

## COBOL

### Canonical version

Works with: OpenCOBOL
      * FIZZBUZZ.COB      * cobc -x -g FIZZBUZZ.COB      *       IDENTIFICATION        DIVISION.       PROGRAM-ID.           fizzbuzz.       DATA                  DIVISION.       WORKING-STORAGE       SECTION.       01 CNT      PIC 9(03) VALUE 1.       01 REM      PIC 9(03) VALUE 0.       01 QUOTIENT PIC 9(03) VALUE 0.       PROCEDURE             DIVISION.      *       PERFORM UNTIL CNT > 100         DIVIDE 15 INTO CNT GIVING QUOTIENT REMAINDER REM         IF REM = 0           THEN             DISPLAY "FizzBuzz " WITH NO ADVANCING           ELSE             DIVIDE 3 INTO CNT GIVING QUOTIENT REMAINDER REM             IF REM = 0               THEN                 DISPLAY "Fizz " WITH NO ADVANCING               ELSE                 DIVIDE 5 INTO CNT GIVING QUOTIENT REMAINDER REM                 IF REM = 0                   THEN                     DISPLAY "Buzz " WITH NO ADVANCING                   ELSE                     DISPLAY CNT " " WITH NO ADVANCING                 END-IF             END-IF         END-IF         ADD 1 TO CNT       END-PERFORM       DISPLAY ""       STOP RUN.

### Simpler version

I know this doesn't have the full-bodied, piquant flavor expected from COBOL, but it is a little shorter.

Works with: OpenCOBOL
Identification division.Program-id. fizz-buzz. Data division.Working-storage section. 01 num pic 999. Procedure division.    Perform varying num from 1 by 1 until num > 100        if function mod (num, 15) = 0 then display "fizzbuzz"        else if function mod (num, 3) = 0 then display "fizz"        else if function mod (num, 5) = 0 then display "buzz"        else display num    end-perform.    Stop run.

### Evaluate Version

I think this shows clearly that it's resolving the problem and illuminating the rules specified

Works with: OpenCOBOL
        IDENTIFICATION DIVISION.       PROGRAM-ID.  FIZZBUZZ.       ENVIRONMENT DIVISION.       DATA DIVISION.       WORKING-STORAGE SECTION.       01  X PIC 999.       01  Y PIC 999.       01  REM3 PIC 999.       01  REM5 PIC 999.       PROCEDURE DIVISION.           PERFORM VARYING X FROM 1 BY 1 UNTIL X > 100               DIVIDE X BY 3 GIVING Y REMAINDER REM3               DIVIDE X BY 5 GIVING Y REMAINDER REM5            EVALUATE REM3 ALSO REM5              WHEN ZERO ALSO ZERO                DISPLAY "FizzBuzz"              WHEN ZERO ALSO ANY                DISPLAY "Fizz"              WHEN ANY ALSO ZERO                DISPLAY "Buzz"              WHEN OTHER                DISPLAY X            END-EVALUATE           END-PERFORM           STOP RUN           . 

### Chase the Fizz

Works with: OpenCOBOL

A solution that simply evaluates and adds.

         >>SOURCE FORMAT FREEidentification division.program-id. fizzbuzz.data division.working-storage section.01  i pic 999.01  fizz pic 999 value 3.01  buzz pic 999 value 5.procedure division.start-fizzbuzz.    perform varying i from 1 by 1 until i > 100         evaluate i also i        when fizz also buzz            display 'fizzbuzz'            add 3 to fizz            add 5 to buzz        when fizz also any            display 'fizz'            add 3 to fizz        when buzz also any            display 'buzz'            add 5 to buzz        when other            display i        end-evaluate    end-perform    stop run    .end program fizzbuzz. 

## Coco

for i from 1 to 100    console.log do       if      i % 15 == 0 then 'FizzBuzz'       else if i % 3 == 0 then 'Fizz'       else if i % 5 == 0 then 'Buzz'       else i
for i from 1 to 100    console.log(['Fizz' unless i % 3] + ['Buzz' unless i % 5] or String(i))

## CoffeeScript

for i in [1..100]  if i % 15 is 0    console.log "FizzBuzz"  else if i % 3 is 0    console.log "Fizz"  else if i % 5 is 0    console.log "Buzz"  else    console.log i
for i in [1..100]  console.log \    if i % 15 is 0      "FizzBuzz"    else if i % 3 is 0      "Fizz"    else if i % 5 is 0      "Buzz"    else      i
for i in [1..100]  console.log(['Fizz' if i % 3 is 0] + ['Buzz' if i % 5 is 0] or i)

## ColdFusion

<Cfloop from="1" to="100" index="i">  <Cfif i mod 15 eq 0>FizzBuzz  <Cfelseif i mod 5 eq 0>Fizz  <Cfelseif i mod 3 eq 0>Buzz  <Cfelse><Cfoutput>#i# </Cfoutput>  </Cfif>      </Cfloop>

cfscript version

<cfscript>result = "";  for(i=1;i<=100;i++){    result=ListAppend(result, (i%15==0) ? "FizzBuzz": (i%5==0) ? "Buzz" : (i%3 eq 0)? "Fizz" : i );  }  WriteOutput(result);</cfscript>

## Comefrom0x10

fizzbuzz  mod_three = 3  mod_five = 5  comefrom fizzbuzz  n  comefrom fizzbuzz if n is mod_three  comefrom fizzbuzz if n is mod_five  n = n + 1   fizz    comefrom fizzbuzz if n is mod_three    'Fizz'...    mod_three = mod_three + 3    linebreak      # would like to write "unless mod_three is mod_five"      comefrom fizz if mod_three - mod_five - 3      ''   buzz    comefrom fizzbuzz if n is mod_five    'Buzz'    mod_five = mod_five + 5   comefrom fizzbuzz if n is 100

## Common Lisp

Solution 1:

(defun fizzbuzz ()  (loop for x from 1 to 100 do    (princ (cond ((zerop (mod x 15)) "FizzBuzz")                 ((zerop (mod x 3))  "Fizz")                 ((zerop (mod x 5))  "Buzz")                 (t                  x)))    (terpri)))

Solution 2:

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

Solution 3:

(defun fizzbuzz ()  (loop for n from 1 to 100     do (format t "~&~[~[FizzBuzz~:;Fizz~]~*~:;~[Buzz~*~:;~D~]~]~%"                (mod n 3) (mod n 5) n)))

Solution 4:

(loop as n from 1 to 100      as fizz = (zerop (mod n 3))      as buzz = (zerop (mod n 5))      as numb = (not (or fizz buzz))      do  (format t   "~&~:[~;Fizz~]~:[~;Buzz~]~:[~;~D~]~%"   fizz buzz numb n))

Solution 5:

(format t "~{~:[~&~;~:*~:(~a~)~]~}"  (loop as n from 1 to 100        as f = (zerop (mod n 3))        as b = (zerop (mod n 5))        collect nil        if f collect 'fizz        if b collect 'buzz        if (not (or f b)) collect n))

Solution 6:

(format t "~{~{~:[~;Fizz~]~:[~;Buzz~]~:[~*~;~d~]~}~%~}"  (loop as n from 1 to 100        as f = (zerop (mod n 3))        as b = (zerop (mod n 5))        collect (list f b (not (or f b)) n)))

Solution 7:

(defun core (x)  (mapcar     #'(lambda (a b) (if (equal 0 (mod x a)) b x))     '(3 5)     '("fizz" "buzz"))) (defun filter-core (x)  (if (equal 1 (length (remove-duplicates x)))    (list (car x))    (remove-if-not #'stringp x))) (defun fizzbuzz (x)  (loop for a from 1 to x do    (print (format nil "~{~a~}" (filter-core (core a)))))) (fizzbuzz 100)

First 16 lines of output:

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16


### Alternate solution

I use Allegro CL 10.1

 ;; Project : FizzBuzz (defun fizzbuzz (&optional n)          (let ((n (or n 1)))          (if (> n 100)              nil              (progn              (let ((mult-3 (is-mult-p n 3))              (mult-5 (is-mult-p n 5)))              (if mult-3                  (princ "Fizz"))              (if mult-5                  (princ "Buzz"))              (if (not (or mult-3 mult-5))                  (princ n))              (princ #\linefeed)              (fizzbuzz (+ n 1)))))))(defun is-mult-p (n multiple)          (= (rem n multiple) 0))(fizzbuzz 1) 

Output:

1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz


## Crystal

1.upto(100) do |v|  p fizz_buzz(v)end def fizz_buzz(value)  word = ""  word += "fizz" if value % 3 == 0  word += "buzz" if value % 5 == 0  word += value.to_s if word.empty?  wordend

A more natural solution with the string building:

1.upto(100) do |n|  case  when n % 15 == 0    puts "FizzBuzz"   when n % 5 == 0    puts "Buzz"  when n % 3 == 0    puts "Fizz"  else    puts n  endend

## CSS

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<style>
li {
list-style-position: inside;
}
li:nth-child(3n), li:nth-child(5n) {
list-style-type: none;
}
li:nth-child(3n)::before {
content:'Fizz';
}
li:nth-child(5n)::after {
content:'Buzz';
}
</style>
</head>
<body>
<ol>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ol>
</body>
</html>


## DeviousYarn

each { x range(1 100)    ?  { divisible(x 3)        p:'Fizz' }    ?  { divisible(x 5)        p:'Buzz' }    -? { !:divisible(x 3)        p:x }    o}

## DUP

FizzBuzz, realized using two different methods for string/character output:

Output to STDOUT via single character output.

[$$3/%[]['F,'i,'z,'z,]?\5/%[]['B,'u,'z,'z,]?*[.][]?10,]c: {define function c: mod 3, mod 5 tests, print proper output}0[100<][1+c;!]# {loop from 1 to 100} Output to STDOUT, using stored strings and a separately defined string output operator: [\[^^>][;,1+]#%%]⇒P {define operator P: print stored string}[$$3/%$[][0$"Fizz"P]?\5/%$[][0$"Buzz"P]?*[$.][]?10,]c: {define function c: mod 3, mod 5 tests, print according output}0[$100<][1+c;!]#                                           {loop from 1 to 100}

## DWScript

var i : Integer; for i := 1 to 100 do begin   if i mod 15 = 0 then      PrintLn('FizzBuzz')   else if i mod 3 = 0 then      PrintLn('Fizz')   else if i mod 5 = 0 then      PrintLn('Buzz')   else PrintLn(i);end;

## Dyalect

var n = 1 while n < 20 {    if n % 15 == 0 {        print("fizzbuzz")    } else if n % 3 == 0 {        print("fizz")    } else if n % 5 == 0 {        print("buzz")    } else {        print(n)    }     n = n + 1}
Output:
1
2
fizz
4
buzz
fizz
7
8
fizz
buzz
11
fizz
13
14
fizzbuzz
16
17
fizz
19

## Déjà Vu

for i range 1 100:	if = 0 % i 15:		"FizzBuzz"	elseif = 0 % i 3:		"Fizz"	elseif = 0 % i 5:		"Buzz"	else:		i	!print

## E

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

## EasyLang

for i = 1 to 100  if i mod 15 = 0    print "FizzBuzz"  elif i mod 5 = 0    print "Buzz"  elif i mod 3 = 0    print "Fizz"  else    print i  ..

## ECL

DataRec := RECORD    STRING  s;END; DataRec MakeDataRec(UNSIGNED c) := TRANSFORM    SELF.s := MAP        (            c % 15 = 0  =>  'FizzBuzz',            c % 3 = 0   =>  'Fizz',            c % 5 = 0   =>  'Buzz',            (STRING)c        );END; d := DATASET(100,MakeDataRec(COUNTER)); OUTPUT(d);

## Eero

#import <Foundation/Foundation.h> int main()  autoreleasepool     for int i in 1 .. 100      s := ''      if i % 3 == 0        s << 'Fizz'      if i % 5 == 0        s << 'Buzz'      Log( '(%d) %@', i, s )   return 0

## Egel

 import "prelude.eg"import "io.ego" using Systemusing IO def fizzbuzz =    [ 100 -> print "100\n"    | N ->         if and ((N%3) == 0) ((N%5) == 0) then             let _ = print "fizz buzz, " in fizzbuzz (N+1)        else if (N%3) == 0 then            let _ = print "fizz, " in fizzbuzz (N+1)        else if (N%5) == 0 then            let _ = print "buzz, " in fizzbuzz (N+1)        else            let _ = print N ", " in fizzbuzz (N+1) ] def main = fizzbuzz 1 

## Eiffel

 class	APPLICATION create	make feature 	make		do			fizzbuzz		end 	fizzbuzz	        --Numbers up to 100, prints "Fizz" instead of multiples of 3, and "Buzz" for multiples of 5.	        --For multiples of both 3 and 5 prints "FizzBuzz".		do			across				1 |..| 100 as c			loop				if c.item \\ 15 = 0 then					io.put_string ("FIZZBUZZ%N")				elseif c.item \\ 3 = 0 then					io.put_string ("FIZZ%N")				elseif c.item \\ 5 = 0 then					io.put_string ("BUZZ%N")				else					io.put_string (c.item.out + "%N")				end			end		end end  

## Ela

open list prt x | x % 15 == 0 = "FizzBuzz"      | x % 3 == 0  = "Fizz"      | x % 5 == 0  = "Buzz"      | else        = x [1..100] |> map prt

## Elixir

### Standard approaches

used case

Enum.each 1..100, fn x ->  IO.puts(case { rem(x,3) == 0, rem(x,5) == 0 } do    { true, true }   -> "FizzBuzz"    { true, false }  -> "Fizz"    { false, true }  -> "Buzz"    { false, false } -> x  end)end

Alternate approach using pipes and cond:

#!/usr/bin/env elixir1..100 |> Enum.map(fn i ->  cond do    rem(i,3*5) == 0 -> "FizzBuzz"    rem(i,3) == 0   -> "Fizz"    rem(i,5) == 0   -> "Buzz"    true            -> i  endend) |> Enum.each(fn i -> IO.puts i end)

used Stream.cycle version:

defmodule RC do  def fizzbuzz(limit \\ 100) do    fizz = Stream.cycle(["", "", "Fizz"])    buzz = Stream.cycle(["", "", "", "", "Buzz"])    Stream.zip(fizz, buzz)    |> Enum.take(limit)    |> Enum.with_index    |> Enum.each(fn {{f,b},i} ->         IO.puts if f<>b=="", do: i+1, else: f<>b       end)  endend RC.fizzbuzz

Yet another approach:

defmodule FizzBuzz do  def fizzbuzz(n) when rem(n, 15) == 0, do: "FizzBuzz"  def fizzbuzz(n) when rem(n,  5) == 0, do: "Buzz"  def fizzbuzz(n) when rem(n,  3) == 0, do: "Fizz"  def fizzbuzz(n),                      do: n  end Enum.each(1..100, &IO.puts FizzBuzz.fizzbuzz &1)

used anonymous function

f = fn(n) when rem(n,15)==0 -> "FizzBuzz"      (n) when rem(n,5)==0  -> "Fizz"      (n) when rem(n,3)==0  -> "Buzz"      (n)                   -> nend for n <- 1..100, do: IO.puts f.(n)

Enum.at version: Returns nil if index is out of bounds.

Enum.each(1..100, fn i ->  str = "#{Enum.at([:Fizz], rem(i,3))}#{Enum.at([:Buzz], rem(i,5))}"  IO.puts if str=="", do: i, else: strend)

### A macro too far

The Stream.cycle version above, but as an overpowered FizzBuzz DSL.

defmodule BadFizz do  # Hand-rolls a bunch of AST before injecting the resulting FizzBuzz code.  defmacrop automate_fizz(fizzers, n) do    # To begin, we need to process fizzers to produce the various components    # we're using in the final assembly. As told by Mickens telling as Antonio    # Banderas, first you must specify a mapping function:    build_parts = (fn {fz, n} ->      ast_ref = {fz |> String.downcase |> String.to_atom, [], __MODULE__}      clist   = List.duplicate("", n - 1) ++ [fz]      cycle   = quote do: unquote(ast_ref) = unquote(clist) |> Stream.cycle       {ast_ref, cycle}    end)     # ...and then a reducing function:    collate = (fn       ({ast_ref, cycle}, {ast_refs, cycles}) ->        {[ast_ref | ast_refs], [cycle | cycles]}    end)     # ...and then, my love, when you are done your computation is ready to run    # across thousands of fizzbuzz:    {ast_refs, cycles} = fizzers    |> Code.eval_quoted([], __ENV__) |> elem(0) # Gotta unwrap this mystery code~    |> Enum.sort(fn ({_, ap}, {_, bp}) -> ap < bp end) # Sort so that Fizz, 3 < Buzz, 5    |> Enum.map(build_parts)     |> Enum.reduce({[], []}, collate)     # Setup the anonymous functions used by Enum.reduce to build our AST components.    # This was previously handled by List.foldl, but ejected because reduce/2's    # default behavior reduces repetition.    #    # ...I was tempted to move these into a macro themselves, and thought better of it.    build_zip    = fn (varname, ast) ->       quote do: Stream.zip(unquote(varname), unquote(ast))    end    build_tuple  = fn (varname, ast) ->       {:{}, [], [varname, ast]}     end    build_concat = fn (varname, ast) ->        {:<>,        [context: __MODULE__, import: Kernel], # Hygiene values may change; accurate to Elixir 1.1.1        [varname, ast]}    end     # Toss cycles into a block by hand, then smash ast_refs into    # a few different computations on the cycle block results.    cycles = {:__block__, [], cycles}    tuple  = ast_refs |> Enum.reduce(build_tuple)    zip    = ast_refs |> Enum.reduce(build_zip)    concat = ast_refs |> Enum.reduce(build_concat)     # Finally-- Now that all our components are assembled, we can put    # together the fizzbuzz stream pipeline. After quote ends, this    # block is injected into the caller's context.    quote do      unquote(cycles)       unquote(zip)      |> Stream.with_index      |> Enum.take(unquote(n))      |> Enum.each(fn       {unquote(tuple), i} ->        ccats = unquote(concat)        IO.puts if ccats == "", do: i + 1, else: ccats      end)    end  end   @doc ~S"""    A fizzing, and possibly buzzing function. Somehow, you feel like you've    seen this before. An old friend, suddenly appearing in Kafkaesque nightmare...     ...or worse, during a whiteboard interview.  """  def fizz(n \\ 100) when is_number(n) do    # In reward for all that effort above, we now have the latest in    # programmer productivity:     #    # A DSL for building arbitrary fizzing, buzzing, bazzing, and more!    [{"Fizz", 3},      {"Buzz", 5}#,     #{"Bar", 7},     #{"Foo", 243}, # -> Always printed last (largest number)     #{"Qux", 34}    ]     |> automate_fizz(n)  endend BadFizz.fizz(100) # => Prints to stdout

## Elm

A bit too simple:

import Html exposing (text)import List exposing (map) main =  [1..100] |> map getWordForNum |> text getWordForNum num =  if num % 15 == 0 then    "FizzBuzz"  else if num % 3 == 0 then    "Fizz"  else if num % 5 == 0 then    "Buzz"  else    String.fromInt num

A bit too clever:

import Html exposing (text)import List exposing (map)import String exposing (join, fromInt) main : Html.Htmlmain =  [1..100] |> map fizzbuzz |> join " " |> text fizzbuzz : Int -> Stringfizzbuzz num =  let    fizz = if num % 3 == 0 then "Fizz" else ""    buzz = if num % 5 == 0 then "Buzz" else ""  in    if fizz == buzz then      fromInt num    else      fizz ++ buzz

## Emacs Lisp

 (defun fizzbuzz (n)   (cond ((and 	  (eq (% n 5) 0) 	  (eq (% n 3) 0))  "FizzBuzz") 	((eq (% n 3) 0)  "Fizz") 	((eq (% n 5) 0)  "Buzz") 	(t  n))) ;; loop & print from 0 to 100(dotimes (i 101) (princ-list (fizzbuzz i))) 

## Erlang

-spec fizzbuzz() -> Result :: string().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,    lists:flatten([[F(N)] ++ ["\n"] || N <- lists:seq(1,100)]).

## ERRE

 PROGRAM FIZZ_BUZZ!! for rosettacode.org!BEGIN FOR A=1 TO 100 DO   IF A MOD 15=0 THEN      PRINT("FizzBuzz")   ELSIF A MOD 3=0 THEN      PRINT("Fizz")   ELSIF A MOD 5=0 THEN      PRINT("Buzz")   ELSE      PRINT(A)   END IF END FOREND PROGRAM 

## Euphoria

Works with: Euphoria version 4.0.0

This is based on the VBScript example.

include std/utils.e function fb( atom n )	sequence fb	if remainder( n, 15 ) = 0 then		fb = "FizzBuzz"	elsif remainder( n, 5 ) = 0 then		fb = "Fizz"	elsif remainder( n, 3 ) = 0 then		fb = "Buzz"	else		fb = sprintf( "%d", n )	end if	return fbend function function fb2( atom n )	return iif( remainder(n, 15) = 0, "FizzBuzz", 		iif( remainder( n, 5 ) = 0, "Fizz", 		iif( remainder( n, 3) = 0, "Buzz", sprintf( "%d", n ) ) ) ) end function for i = 1 to 30 do	printf( 1, "%s ", { fb( i ) } )end for puts( 1, "\n" ) for i = 1 to 30 do	printf( 1, "%s ", { fb2( i ) } )end for puts( 1, "\n" )

## F#

let fizzbuzz n =    match n%3 = 0, n%5 = 0 with    | true, false -> "fizz"    | false, true -> "buzz"    | true, true  -> "fizzbuzz"    | _ -> string n let printFizzbuzz() =    [1..100] |> List.iter (fizzbuzz >> printfn "%s")
[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)    

Another example using (unnecessary) partial active pattern :D

let (|MultipleOf|_|) divisors number =    if Seq.exists ((%) number >> (<>) 0) divisors    then None    else Some () let fizzbuzz = function| MultipleOf [3; 5] -> "fizzbuzz"| MultipleOf [3]    -> "fizz"| MultipleOf [5]    -> "buzz"| n                 -> string n { 1 .. 100 }|> Seq.iter (fizzbuzz >> printfn "%s")

## Factor

USING: math kernel io math.functions math.parser math.ranges ;IN: fizzbuzz: fizz ( n -- str ) 3 divisor? "Fizz" "" ? ;: buzz ( n -- str ) 5 divisor? "Buzz" "" ? ;: fizzbuzz ( n -- str ) dup [ fizz ] [ buzz ] bi append [ number>string ] [ nip ] if-empty ;: main ( -- ) 100 [1,b] [ fizzbuzz print ] each ;MAIN: main

More flexible variant without divisibility tests.

 USING: kernel sequences arrays generalizations fry math math.parser prettyprint ;IN: fizzbuzz : zz ( m seq -- v ) dup length 1 <array> V{ } clone 4 -nrot 1 4 -nrot 3 nrot '[ dup _ <= ]  3 -nrot '[    "" _ [ _ [ swap execute( str n -- str n ) ] change-nth ] each-index    dup empty? [ drop dup number>string ] [ ] if swapd suffix! swap 1 +  ]  while drop ; : fizz ( str n -- str n ) dup 3 < [ 1 + ] [ drop "Fizz" append 1 ] if ;: buzz ( str n -- str n ) dup 5 < [ 1 + ] [ drop "Buzz" append 1 ] if ;: quxx ( str n -- str n ) dup 7 < [ 1 + ] [ drop "Quxx" append 1 ] if ;: FizzBuzzQuxx ( m -- v ) { fizz buzz quxx } zz ;: FizzBuzzQuxx-100 ( -- ) 100 FizzBuzzQuxx . ; MAIN: FizzBuzzQuxx-100 

## Falcon

for i in [1:101]    switch i % 15    case 0        : > "FizzBuzz"    case 5,10     : > "Buzz"    case 3,6,9,12 : > "Fizz"    default       : > i    endend

## Fantom

class FizzBuzz{  public static Void main ()  {    for (Int i:=1; i <= 100; ++i)    {      if (i % 15 == 0)        echo ("FizzBuzz")      else if (i % 3 == 0)        echo ("Fizz")      else if (i % 5 == 0)         echo ("Buzz")       else        echo (i)    }  }}

## FBSL

No 'MOD 15' needed.

#APPTYPE CONSOLE DIM numbers AS STRINGDIM imod5 AS INTEGERDIM imod3 AS INTEGER FOR DIM i = 1 TO 100    numbers = ""    imod3 = i MOD 3    imod5 = i MOD 5    IF NOT imod3 THEN numbers = "Fizz"    IF NOT imod5 THEN numbers = numbers & "Buzz"    IF imod3 AND imod5 THEN numbers = i    PRINT numbers, " ";NEXT PAUSE
Output:
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz Fiz
z 22 23 Fizz Buzz 26 Fizz 28 29 FizzBuzz 31 32 Fizz 34 Buzz Fizz 37 38 Fizz Buzz
41 Fizz 43 44 FizzBuzz 46 47 Fizz 49 Buzz Fizz 52 53 Fizz Buzz 56 Fizz 58 59 Fi
zzBuzz 61 62 Fizz 64 Buzz Fizz 67 68 Fizz Buzz 71 Fizz 73 74 FizzBuzz 76 77 Fizz
79 Buzz Fizz 82 83 Fizz Buzz 86 Fizz 88 89 FizzBuzz 91 92 Fizz 94 Buzz Fizz 97
98 Fizz Buzz
Press any key to continue...


## FOCAL

FITR is a built-in function that truncates a floating-point number to an integer. Note that FOCAL uses an arithmetic (three-way) IF statement, rather like early Fortran.

01.10 FOR I=1,100; DO 2.001.20 QUIT 02.10 SET ZB=I/15 - FITR(I/15)02.20 IF (ZB) 2.4, 2.3, 2.402.30 TYPE "FizzBuzz" !02.35 RETURN02.40 SET Z=I/3 - FITR(I/3)02.50 IF (Z) 2.7, 2.6, 2.702.60 TYPE "Fizz" !02.65 RETURN02.70 SET B=I/5 - FITR(I/5)02.80 IF (B) 2.99, 2.9, 2.9902.90 TYPE "Buzz" !02.95 RETURN02.99 TYPE %3, I, !

## 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 [email protected] if drop pad count type else . then ; : zz ( n -- )  1+ 1 do i .fizzbuzz cr loop ;100 zz

### the well factored approach

SYNONYM is a Forth200x word.

SYNONYM NOT INVERT \ Bitwise boolean not : Fizz?  ( n -- ? )  3 MOD 0=  DUP IF ." Fizz" THEN ;: Buzz?  ( n -- ? )  5 MOD 0=  DUP IF ." Buzz" THEN ;: ?print  ( n ? -- )  IF . THEN ;: FizzBuzz  ( -- )   101 1 DO CR  I  DUP Fizz? OVER Buzz? OR  NOT ?print  LOOP ; FizzBuzz

### the unrolled approach

: n     ( n -- n+1 )    dup .         1+ ;: f     ( n -- n+1 )    ." Fizz "     1+ ;: b     ( n -- n+1 )    ." Buzz "     1+ ;: fb    ( n -- n+1 )    ." FizzBuzz " 1+ ;: fb10  ( n -- n+10 )   n n f n b f n n f b ;: fb15  ( n -- n+15 )   fb10 n f n n fb ;: fb100 ( n -- n+100 )  fb15 fb15 fb15 fb15 fb15 fb15 fb10 ;: .fizzbuzz ( -- )      1 fb100 drop ;

## Fortran

In ANSI FORTRAN 77 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 doend program fizzbuzz_if

This example uses If statements to print "Fizz" and "Buzz" next to each other if the number is divisible by 3 and 5 by waiting to use a line break until after the If statements.

program FizzBuzzimplicit noneinteger :: i = 1 do i = 1, 100    if (Mod(i,3) == 0)write(*,"(A)",advance='no')  "Fizz"    if (Mod(i,5) == 0)write(*,"(A)",advance='no') "Buzz"    if (Mod(i,3) /= 0 .and. Mod(i,5) /=0 )write(*,"(I3)",advance='no') i    print *, ""end doend program FizzBuzz 

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

## Frege

gen n word = cycle (take (n - 1) (repeat "") ++ [word])pattern = zipWith (++) (gen 3 "fizz") (gen 5 "buzz")fizzbuzz = zipWith combine pattern [1..] where    combine word number = if null word                             then show number                             else wordshow $take 100 fizzbuzz ## Frink for i = 1 to 100{ flag = false if i mod 3 == 0 { flag = true print["Fizz"] } if i mod 5 == 0 { flag = true print["Buzz"] } if flag == false print[i] println[]} ## FutureBasic  include "ConsoleWindow" dim as short fizz, buzz, idim as Str15 s for i = 1 to 100 fizz = (i mod 3 ) buzz = (i mod 5 ) if (i) if fizz + buzz == 0 then print i; ".", "FizzBuzz" : exit if if fizz == 0 then print i; ".", "Fizz" : exit if if buzz == 0 then print i; ".", "Buzz" : exit if print i end ifnext i  Output:  1 2 3. Fizz 4 5. Buzz 6. Fizz 7 8 9. Fizz 10. Buzz 11 12. Fizz 13 14 15. FizzBuzz 16 17 18. Fizz 19 20. Buzz 21. Fizz 22 23 24. Fizz 25. Buzz 26 27. Fizz 28 29 30. FizzBuzz 31 32 33. Fizz 34 35. Buzz 36. Fizz 37 38 39. Fizz 40. Buzz 41 42. Fizz 43 44 45. FizzBuzz 46 47 48. Fizz 49 50. Buzz 51. Fizz 52 53 54. Fizz 55. Buzz 56 57. Fizz 58 59 60. FizzBuzz 61 62 63. Fizz 64 65. Buzz 66. Fizz 67 68 69. Fizz 70. Buzz 71 72. Fizz 73 74 75. FizzBuzz 76 77 78. Fizz 79 80. Buzz 81. Fizz 82 83 84. Fizz 85. Buzz 86 87. Fizz 88 89 90. FizzBuzz 91 92 93. Fizz 94 95. Buzz 96. Fizz 97 98 99. Fizz 100. Buzz  ## Gambas Public Sub Main()Dim siCount As ShortDim sText As String For siCount = 1 To 100 sText = "" If siCount Mod 3 = 0 Then sText = "Fizz" If siCount Mod 5 = 0 Then sText = "Buzz" If siCount Mod 15 = 0 Then sText = "FizzBuzz" If sText Then Print sText Else Print siCountNext End Output: 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz Fizz 22 23 Fizz Buzz 26 Fizz 28 29 FizzBuzz 31 32 Fizz 34 Buzz Fizz 37 38 Fizz Buzz 41 Fizz 43 44 FizzBuzz 46 47 Fizz 49 Buzz Fizz 52 53 Fizz Buzz 56 Fizz 58 59 FizzBuzz 61 62 Fizz 64 Buzz Fizz 67 68 Fizz Buzz 71 Fizz 73 74 FizzBuzz 76 77 Fizz 79 Buzz Fizz 82 83 Fizz Buzz 86 Fizz 88 89 FizzBuzz 91 92 Fizz 94 Buzz Fizz 97 98 Fizz Buzz  ## GAP FizzBuzz := function() local i; for i in [1 .. 100] do if RemInt(i, 15) = 0 then Print("FizzBuzz\n"); elif RemInt(i, 3) = 0 then Print("Fizz\n"); elif RemInt(i, 5) = 0 then Print("Buzz\n"); else Print(i, "\n"); fi; od;end; ## Genyris  @prefix u "http://www.genyris.org/lang/utilities#" def fizzbuzz (n) map-left ^((3 = 'fizz') (5 = 'buzz')) lambda (d) cond (equal? 0 (% n d!left)) d!right else '' for n in (range 1 100) define fb (''(.join (fizzbuzz n))) u:format "%a\n" cond (equal? fb '') n else fb  ## GFA Basic  ' Fizz Buzz'FOR i%=1 TO 100 IF i% MOD 15=0 PRINT "FizzBuzz" ELSE IF i% MOD 3=0 PRINT "Fizz" ELSE IF i% MOD 5=0 PRINT "Buzz" ELSE PRINT i% ENDIFNEXT i%  ## Go ### switch/case approach package main import "fmt" func main() { for i := 1; i <= 100; i++ { switch { case i%15==0: fmt.Println("FizzBuzz") case i%3==0: fmt.Println("Fizz") case i%5==0: fmt.Println("Buzz") default: fmt.Println(i) } }} ### map approach package main import "fmt" func main() { for i := 1; i <= 100; i++ { fmt.Println(map[bool]map[bool]interface{}{ false: {false: i, true: "Fizz"}, true: {false: "Buzz", true: "FizzBuzz"}, }[i%5 == 0][i%3 == 0]) }} ## Golo module FizzBuzz augment java.lang.Integer { function getFizzAndOrBuzz = |this| -> match { when this % 15 == 0 then "FizzBuzz" when this % 3 == 0 then "Fizz" when this % 5 == 0 then "Buzz" otherwise this }} function main = |args| { foreach i in [1..101] { println(i: getFizzAndOrBuzz()) }}  ## Gosu for (i in 1..100) { if (i % 3 == 0 && i % 5 == 0) { print("FizzBuzz") continue } if (i % 3 == 0) { print("Fizz") continue } if (i % 5 == 0) { print("Buzz") continue } // default print(i) } One liner version (I added new lines to better readability but when you omit them it's one liner): // note that compiler reports error (I don't know why) but still it's workingfor (i in 1..100) { print(i % 5 == 0 ? i % 3 == 0 ? "FizzBuzz" : "Buzz" : i % 3 == 0 ? "Fizz" : i)} ## Groovy 1.upto(100) { i -> println "${i % 3 ? '' : 'Fizz'}${i % 5 ? '' : 'Buzz'}" ?: i } ## GW-BASIC ## Haskell Variant directly implementing the specification: fizzbuzz :: Int -> Stringfizzbuzz x | f 15 = "FizzBuzz" | f 3 = "Fizz" | f 5 = "Buzz" | otherwise = show x where f = (0 ==) . rem x main :: IO ()main = mapM_ (putStrLn . fizzbuzz) [1 .. 100] fizzbuzz :: Int -> Stringfizzbuzz n = '\n' : if null (fizz ++ buzz) then show n else fizz ++ buzz where fizz = if mod n 3 == 0 then "Fizz" else "" buzz = if mod n 5 == 0 then "Buzz" else "" main :: IO ()main = putStr$ concatMap fizzbuzz [1 .. 100]

Does not perform the mod 15 step, extesible to arbitrary addtional tests, ex: [bar| n mod 7 == 0].

main = mapM_ (putStrLn . fizzbuzz) [1..100] fizzbuzz n =     show n <|> [fizz| n mod 3 == 0] ++                [buzz| n mod 5 == 0] -- A simple default choice operator. -- Defaults if both fizz and buzz fail, concats if any succeed.infixr 0 <|>d <|> [] = d_ <|> x = concat x fizz = "Fizz"buzz = "Buzz"

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

main = mapM_ putStrLn $take 100$ zipWith show_number_or_fizzbuzz [1..] fizz_buzz_list            show_number_or_fizzbuzz x y = if null y then show x else y fizz_buzz_list = zipWith (++) (cycle ["","","Fizz"]) (cycle ["","","","","Buzz"])

Or in terms (still without mod or rem) of a single zipWith3:

import Data.List (zipWith3)import Data.Bool (bool) fizzBuzz :: [String]fizzBuzz =  zipWith3    (\f b n ->        let fb = f ++ b        in bool fb n (null fb))    (cycle $replicate 2 [] ++ ["fizz"]) (cycle$ replicate 4 [] ++ ["buzz"])    (show <$> [1 ..]) main :: IO ()main = mapM_ putStrLn$ take 100 fizzBuzz

or using an applicative test:

import Data.Bool (bool) fizzBuzz :: [String]fizzBuzz =  let fb n k = cycle (replicate (pred n) [] ++ [k])  in zipWith       (flip . bool <*> null)       (zipWith (++) (fb 3 "fizz") (fb 5 "buzz"))       (show <$> [1 ..]) main :: IO ()main = mapM_ putStrLn$ take 100 fizzBuzz

Using heavy artillery (needs the mtl package):

 import Control.Monad.Stateimport Control.Monad.Transimport Control.Monad.Writer main = putStr $execWriter$ mapM_ (flip execStateT True . fizzbuzz) [1..100] fizzbuzz :: Int -> StateT Bool (Writer String) ()fizzbuzz x = do when (x mod 3 == 0) $tell "Fizz" >> put False when (x mod 5 == 0)$ tell "Buzz" >> put False get >>= (flip when $tell$ show x) tell "\n"

Using guards plus where.

fizzBuzz :: (Integral a) => a -> StringfizzBuzz i  | fizz && buzz = "FizzBuzz"  | fizz         = "Fizz"  | buzz         = "Buzz"  | otherwise    = show i  where fizz = i mod 3 == 0        buzz = i mod 5 == 0 main = mapM_ (putStrLn . fizzBuzz) [1..100]

An elegant solution exploiting monoidal and applicative properties of functions:

## Inform 6

[ Main i;  for(i = 1: i <= 100: i++)  {    if(i % 3 == 0) print "Fizz";    if(i % 5 == 0) print "Buzz";    if(i % 3 ~= 0 && i % 5 ~= 0) print i;     print "^";  }];

## Inform 7

(Does not work in the current version of Inform 7)

Home is a room. When play begins:	repeat with N running from 1 to 100:		let printed be false;		if the remainder after dividing N by 3 is 0:			say "Fizz";			now printed is true;		if the remainder after dividing N by 5 is 0:			say "Buzz";			now printed is true;		if printed is false, say N;		say ".";	end the story.

(Version which is less "programmy", and more in the natural English style of interactive fiction.)

The space is a room.  An item is a kind of thing.  In the space are 100 items. To say the name:	let the count be the number of items carried by the player;	say "[if the count is the count to the nearest 15]fizzbuzz.[otherwise if the count is the count to the nearest 3]fizz.[otherwise if the count is the count to the nearest 5]buzz.[otherwise][the count in words].". To count:	if an item is in the space	begin;		let the next one be a random item in the space; silently try taking the next one;		say "[the name]" in sentence case;		count;		end the story;	end if. When play begins: count.  Use no scoring.

## Io

Here's one way to do it:

for(a,1,100,   if(a % 15 == 0) then(      "FizzBuzz" println   ) elseif(a % 3 == 0) then(      "Fizz" println   ) elseif(a % 5 == 0) then(      "Buzz" println   ) else (      a println   ))

And here's a port of the Ruby version, which I personally prefer:

a := 0; b := 0for(n, 1, 100,    if(a = (n % 3) == 0, "Fizz" print);    if(b = (n % 5) == 0, "Buzz" print);    if(a not and b not, n print);    "\n" print)

And here is another more idiomatic version:

for (n, 1, 100,    fb := list (        if (n % 3 == 0, "Fizz"),        if (n % 5 == 0, "Buzz")) select (isTrue)     if (fb isEmpty, n, fb join) println)

## Ioke

(1..100) each(x,  cond(    (x % 15) zero?, "FizzBuzz" println,    (x % 3) zero?, "Fizz" println,    (x % 5) zero?, "Buzz" println  ))

## Iptscrae

; FizzBuzz in Iptscrae1 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

## J

Solution _1: Using agenda (@.) as a switch:

    classify =: +/@(1 2 * 0 = 3 5&|~)   (":@]('Fizz'"_)('Buzz'"_)('FizzBuzz'"_) @. classify "0)  >:i.100

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

Solution 2 (has taste of table-driven template programming)

CRT0=: 2 : ' (, 0 = +./)@(0 = m | ]) ;@# n , <@": 'NB. Rather (, 0 = +./) than (, +:/) because designed forNB. 3 5 7 CRT0 (;:'Chinese Remainder Period') "0 >: i. */3 5 7FizzBuzz=: 3 5 CRT0 (;:'Fizz Buzz') FizzBuzz"0 >: i.100

Solution 3 (depends on an obsolete feature of @ in fg[email protected])

'f   b   fb'  =: ('Fizz'"_)  ('Buzz'"_)  (f , b)'cm3 cm5 cm15'=: (3&|)       (5&|)       (15&|)  (0&[email protected])FizzBuzz=: ":  f @. cm3  b @. cm5  fb @. cm15  NB. also:FizzBuzz=: ":  f @. cm3  b @. cm5  (f,b) @. (cm3 *. cm5) FizzBuzz"0 >: i.100

Solution 4 (relatively concise):

   ;:inv}.(":&.> [^:(0 = #@])&.> [: ,&.>/ (;:'Fizz Buzz') #&.>~ 0 = 3 5 |/ ])i.1011 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz Fizz 22 23 Fizz Buzz 26 Fizz 28 29 FizzBuzz 31 32 Fizz 34 Buzz Fizz 37 38 Fizz Buzz 41 Fizz 43 44 FizzBuzz 46 47 Fizz 49 Buzz Fizz 52 53 Fizz Buzz 56 Fizz 58 59 FizzBuzz 61 62 Fiz...

Here's some intermediate results for subexpressions of this last version (but with a shorter list of numbers):

   i.100 1 2 3 4 5 6 7 8 9   (3 5 |/ ])i.100 1 2 0 1 2 0 1 2 00 1 2 3 4 0 1 2 3 4   (0=3 5 |/ ])i.101 0 0 1 0 0 1 0 0 11 0 0 0 0 1 0 0 0 0   (;:'Fizz Buzz')┌────┬────┐│Fizz│Buzz│└────┴────┘   ((;:'Fizz Buzz') #&.>~0=3 5 |/ ])i.10┌────┬┬┬────┬┬────┬────┬┬┬────┐│Fizz│││Fizz││    │Fizz│││Fizz│├────┼┼┼────┼┼────┼────┼┼┼────┤│Buzz│││    ││Buzz│    │││    │└────┴┴┴────┴┴────┴────┴┴┴────┘   ([: ,&.>/ (;:'Fizz Buzz') #&.>~0=3 5 |/ ])i.10┌────────┬┬┬────┬┬────┬────┬┬┬────┐│FizzBuzz│││Fizz││Buzz│Fizz│││Fizz│└────────┴┴┴────┴┴────┴────┴┴┴────┘   (":&.>)i.10┌─┬─┬─┬─┬─┬─┬─┬─┬─┬─┐│0│1│2│3│4│5│6│7│8│9│└─┴─┴─┴─┴─┴─┴─┴─┴─┴─┘   (":&.> [^:(0 = #@])&.> [: ,&.>/ (;:'Fizz Buzz') #&.>~0=3 5 |/ ])i.10┌────────┬─┬─┬────┬─┬────┬────┬─┬─┬────┐│FizzBuzz│1│2│Fizz│4│Buzz│Fizz│7│8│Fizz│└────────┴─┴─┴────┴─┴────┴────┴─┴─┴────┘   }.(":&.> [^:(0 = #@])&.> [: ,&.>/ (;:'Fizz Buzz') #&.>~0=3 5 |/ ])i.10┌─┬─┬────┬─┬────┬────┬─┬─┬────┐│1│2│Fizz│4│Buzz│Fizz│7│8│Fizz│└─┴─┴────┴─┴────┴────┴─┴─┴────┘   ;:inv}.(":&.> [^:(0 = #@])&.> [: ,&.>/ (;:'Fizz Buzz') #&.>~0=3 5 |/ ])i.101 2 Fizz 4 Buzz Fizz 7 8 Fizz

## Janet

 (loop [i :range [1 101]       :let [fizz (zero? (% i 3))             buzz (zero? (% i 5))]]  (print (cond           (and fizz buzz) "fizzbuzz"           fizz "fizz"           buzz "buzz"           i)))

## Java

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

## JavaScript

### ES5

var fizzBuzz = function () {  var i, output;  for (i = 1; i < 101; i += 1) {    output = '';    if (!(i % 3)) { output += 'Fizz'; }    if (!(i % 5)) { output += 'Buzz'; }    console.log(output || i);//empty string is false, so we short-circuit  }};

Alternate version with ghetto pattern matching

for (var i = 1; i <= 100; i++) {  console.log({    truefalse: 'Fizz',     falsetrue: 'Buzz',     truetrue: 'FizzBuzz'  }[(i%3==0) + '' + (i%5==0)] || i)}

Or very tersely:

for(i=1;i<101;i++)console.log((x=(i%3?'':'Fizz')+(i%5?'':'Buzz'))?x:i);

Or with even less characters:

for(i=1;i<101;i++)console.log((i%3?'':'Fizz')+(i%5?'':'Buzz')||i)

Or, in a more functional style, without mutations

(function rng(i) {    return i ? rng(i - 1).concat(i) : []})(100).map(    function (n) {        return n % 3 ? (            n % 5 ? n : "Buzz"        ) : (            n % 5 ? "Fizz" : "FizzBuzz"        )    }).join(' ')

### ES6

(() => {     // FIZZBUZZ --------------------------------------------------------------     // fizzBuzz :: Int -> String    const fizzBuzz = n =>        caseOf(n, [            [x => x % 15 === 0, "FizzBuzz"],            [x => x % 3 === 0, "Fizz"],            [x => x % 5 === 0, "Buzz"]        ], n.toString());     // GENERIC FUNCTIONS -----------------------------------------------------     // caseOf :: a -> [(a -> Bool, b)] -> b -> b    const caseOf = (e, pvs, otherwise) =>        pvs.reduce((a, [p, v]) =>            a !== otherwise ? a : (p(e) ? v : a), otherwise);     // enumFromTo :: Int -> Int -> [Int]    const enumFromTo = (m, n) =>        Array.from({            length: Math.floor(n - m) + 1        }, (_, i) => m + i);     // map :: (a -> b) -> [a] -> [b]    const map = (f, xs) => xs.map(f);     // unlines :: [String] -> String    const unlines = xs => xs.join('\n');     // TEST ------------------------------------------------------------------    return unlines(        map(fizzBuzz, enumFromTo(1, 100))    );})();

A functional implementation:

const factors = [[3, 'Fizz'], [5, 'Buzz']]const fizzBuzz = num => factors.map(([factor,text]) => (num % factor)?'':text).join('') || numconst range1 = x => [...Array(x+1).keys()].slice(1)const outputs = range1(100).map(fizzBuzz) console.log(outputs.join('\n'))

Or composing generic functions, and without use of modulo (or other) numeric tests:

Translation of: Python
Translation of: Haskell

fizzbuzz:{  v:1+!x  i:(&0=)'v!/:3 5 15  r:@[v;i 0;{"Fizz"}]  r:@[r;i 1;{"Buzz"}]  @[r;i 2;{"FizzBuzz"}]} 0:$fizzbuzz 100 ### Solution 3 For kona: {,/$(s;x)@~#s:Fizz[email protected]&~x!'3 5}'1+!30

For k6 and oK, change x!'3 5 to 3 5!'x.

## Kamailio Script

To run it, send a SIP message to the server and FizzBuzz will appear in the logs.

This will only work up to 100 because Kamailio terminates all while loops after 100 iterations.

# FizzBuzzlog_stderror=yesloadmodule "pv"loadmodule "xlog" route {    $var(i) = 1; while ($var(i) <= 1000) {        if ($var(i) mod 15 == 0) { xlog("FizzBuzz\n"); } else if ($var(i) mod 5 == 0) {            xlog("Buzz\n");        } else if ($var(i) mod 3 == 0) { xlog("Fizz\n"); } else { xlog("$var(i)\n");        }        $var(i) =$var(i) + 1;    }}

## Kaya

// fizzbuzz in Kayaprogram fizzbuzz; Void fizzbuzz(Int size) {    for i in [1..size] {        if (i % 15 == 0) {            putStrLn("FizzBuzz");        } else if (i % 5 == 0) {            putStrLn("Buzz");        } else if (i % 3 == 0) {            putStrLn("Fizz");        } else {            putStrLn( string(i) );        }    }} Void main() {    fizzbuzz(100);}

## Klong

 {:[0=x!15;:FizzBuzz:|0=x!5;:Buzz:|0=x!3;:Fizz;x]}'1+!100

## Kotlin

### Imperative solution

fun fizzBuzz() {    for (number in 1..100) {        println(            when {                number % 15 == 0 -> "FizzBuzz"                number % 3 == 0 -> "Fizz"                number % 5 == 0 -> "Buzz"                else -> number            }        )    }}

### Functional solution 1

fun fizzBuzz1() {    fun fizzBuzz(x: Int) = if (x % 15 == 0) "FizzBuzz" else x.toString()    fun fizz(x: Any) = if (x is Int && x % 3 == 0) "Buzz" else x    fun buzz(x: Any) = if (x is Int && x.toInt() % 5 == 0) "Fizz" else x     (1..100).map { fizzBuzz(it) }.map { fizz(it) }.map { buzz(it) }.forEach { println(it) }}

### Functional solution 2

fun fizzBuzz2() {    fun fizz(x: Pair<Int, StringBuilder>) = if(x.first % 3 == 0) x.apply { second.append("Fizz") } else x    fun buzz(x: Pair<Int, StringBuilder>) = if(x.first % 5 == 0) x.apply { second.append("Buzz") } else x    fun none(x: Pair<Int, StringBuilder>) = if(x.second.isBlank()) x.second.apply { append(x.first) } else x.second     (1..100).map { Pair(it, StringBuilder()) }            .map { fizz(it) }            .map { buzz(it) }            .map { none(it) }            .forEach { println(it) }}

### Short version with mapOf

 fun fizzBuzz() {    (1..100).forEach { println(mapOf(0 to it, it % 3 to "Fizz", it % 5 to "Buzz", it % 15 to "FizzBuzz")[0]) }}

## KQL

 range i from 1 to 100 step 1| project Result =    case(        i % 15 == 0, "FizzBuzz",        i % 3 == 0, "Fizz",        i % 5 == 0, "Buzz",        tostring(i)    )

## LabVIEW

This image is a VI Snippet, an executable image of LabVIEW code. The LabVIEW version is shown on the top-right hand corner. You can download it, then drag-and-drop it onto the LabVIEW block diagram from a file browser, and it will appear as runnable, editable code.

## langur

for .i of 100 {    writeln given(0; .i rem 15: "FizzBuzz"; .i rem 5: "Buzz"; .i rem 3: "Fizz"; .i)}
Works with: langur version 0.8.1
for .i of 100 {    writeln if(.i div 15: "FizzBuzz"; .i div 5: "Buzz"; .i div 3: "Fizz"; .i)}

## Lasso

with i in generateSeries(1, 100)select ((#i % 3 == 0 ? 'Fizz' | '') + (#i % 5 == 0 ? 'Buzz' | '') || #i)

## LaTeX

Library: ifthen
Library: intcalc

This version uses the ifthen and intcalc packages. There sure are more native solutions including solutions in plain TeX, but for me this is a readable and comprehensible one.

\documentclass{minimal}\usepackage{ifthen}\usepackage{intcalc} \newcounter{mycount}\newboolean{fizzOrBuzz} \newcommand\fizzBuzz[1]{%\setcounter{mycount}{1}\whiledo{\value{mycount}<#1}    {	\setboolean{fizzOrBuzz}{false}	\ifthenelse{\equal{\intcalcMod{\themycount}{3}}{0}}{\setboolean{fizzOrBuzz}{true}Fizz}{}	\ifthenelse{\equal{\intcalcMod{\themycount}{5}}{0}}{\setboolean{fizzOrBuzz}{true}Buzz}{}	\ifthenelse{\boolean{fizzOrBuzz}}{}{\themycount}	\stepcounter{mycount}	\\    }} \begin{document}    \fizzBuzz{101}\end{document}

## LIL

# fizzbuzz in LILfor {set i 1} {$i <= 100} {inc i} { set show "" if {[expr$i % 3 == 0]} {set show "Fizz"}    if {[expr $i % 5 == 0]} {set show$show"Buzz"}    if {[expr [length $show] == 0]} {set show$i}    print $show} Output: prompt$ lil fizzbuzz.lil | sed -n '1,16p'
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16

## LiveCode

repeat with i = 1 to 100    switch        case i mod 15 = 0            put "FizzBuzz" & cr after fizzbuzz            break        case i mod 5 = 0            put "Buzz" & cr after fizzbuzz            break        case i mod 3 = 0            put "Fizz" & cr after fizzbuzz            break        default            put i & cr after fizzbuzz    end switch end repeatput fizzbuzz

## LiveScript

[1 to 100] map -> [k + \zz for k, v of {Fi: 3, Bu: 5} | it % v < 1] * '' || it

## LLVM

; ModuleID = 'fizzbuzz.c'; source_filename = "fizzbuzz.c"; target datalayout = "e-m:w-i64:64-f80:128-n8:16:32:64-S128"; target triple = "x86_64-pc-windows-msvc19.21.27702" ; This is not strictly LLVM, as it uses the C library function "printf".; LLVM does not provide a way to print values, so the alternative would be; to just load the string into memory, and that would be boring. ; Additional comments have been inserted, as well as changes made from the output produced by clang such as putting more meaningful labels for the jumps $"\[email protected][email protected][email protected]" = comdat any$"\[email protected][email protected][email protected]" = comdat any$"\[email protected][email protected][email protected]" = comdat any$"\[email protected][email protected][email protected]" = comdat any ;--- String constant defintions@"\[email protected][email protected][email protected]" = linkonce_odr unnamed_addr constant [10 x i8] c"FizzBuzz\0A\00", comdat, align 1@"\[email protected][email protected][email protected]" = linkonce_odr unnamed_addr constant [6 x i8] c"Fizz\0A\00", comdat, align 1@"\[email protected][email protected][email protected]" = linkonce_odr unnamed_addr constant [6 x i8] c"Buzz\0A\00", comdat, align 1@"\[email protected][email protected][email protected]" = linkonce_odr unnamed_addr constant [4 x i8] c"%d\0A\00", comdat, align 1 ;--- The declaration for the external C printf function.declare i32 @printf(i8*, ...) ; Function Attrs: noinline nounwind optnone uwtabledefine i32 @main() #0 {  %1 = alloca i32, align 4  store i32 1, i32* %1, align 4;--- It does not seem like this branch can be removed  br label %loop ;--- while (i <= 100)loop:  %2 = load i32, i32* %1, align 4  %3 = icmp sle i32 %2, 100  br i1 %3, label %divisible_15, label %finished ;--- if (i % 15 == 0)divisible_15:  %4 = load i32, i32* %1, align 4  %5 = srem i32 %4, 15  %6 = icmp eq i32 %5, 0  br i1 %6, label %print_fizzbuzz, label %divisible_3 ;--- Print 'FizzBuzz'print_fizzbuzz:  %7 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([10 x i8], [10 x i8]* @"\[email protected][email protected][email protected]", i32 0, i32 0))  br label %next ;--- if (i % 3 == 0)divisible_3:  %8 = load i32, i32* %1, align 4  %9 = srem i32 %8, 3  %10 = icmp eq i32 %9, 0  br i1 %10, label %print_fizz, label %divisible_5 ;--- Print 'Fizz'print_fizz:  %11 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([6 x i8], [6 x i8]* @"\[email protected][email protected][email protected]", i32 0, i32 0))  br label %next ;--- if (i % 5 == 0)divisible_5:  %12 = load i32, i32* %1, align 4  %13 = srem i32 %12, 5  %14 = icmp eq i32 %13, 0  br i1 %14, label %print_buzz, label %print_number ;--- Print 'Buzz'print_buzz:  %15 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([6 x i8], [6 x i8]* @"\[email protected][email protected][email protected]", i32 0, i32 0))  br label %next ;--- Print the numberprint_number:  %16 = load i32, i32* %1, align 4  %17 = call i32 (i8*, ...) @printf(i8* getelementptr inbounds ([4 x i8], [4 x i8]* @"\[email protected][email protected][email protected]", i32 0, i32 0), i32 %16);--- It does not seem like this branch can be removed  br label %next ;--- i = i + 1next:  %18 = load i32, i32* %1, align 4  %19 = add nsw i32 %18, 1  store i32 %19, i32* %1, align 4  br label %loop ;--- exit mainfinished:  ret i32 0} attributes #0 = { noinline nounwind optnone uwtable "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "no-frame-pointer-elim"="false" "no-infs-fp-math"="false" "no-jump-tables"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "target-cpu"="x86-64" "target-features"="+fxsr,+mmx,+sse,+sse2,+x87" "unsafe-fp-math"="false" "use-soft-float"="false" } !llvm.module.flags = !{!0, !1}!llvm.ident = !{!2} !0 = !{i32 1, !"wchar_size", i32 2}!1 = !{i32 7, !"PIC Level", i32 2}!2 = !{!"clang version 6.0.1 (tags/RELEASE_601/final)"}

## Lobster

include "std.lobster" forbias(100, 1) i:    fb := (i % 3 == 0 and "fizz" or "") +          (i % 5 == 0 and "buzz" or "")    print fb.length and fb or "" + i

## Logo

to fizzbuzz :n  output cond [ [[equal? 0 modulo :n 15] "FizzBuzz]                [[equal? 0 modulo :n  5] "Buzz]                [[equal? 0 modulo :n  3] "Fizz]                [else :n] ]end repeat 100 [print fizzbuzz #]

"cond" was undefined in Joshua Bell's online interpreter. So here is a version that works there. It also works in UCB logo by using # instead of "repcount". This version also factors away modulo 15:

to fizzbuzz :n make "c "  if equal? 0 modulo :n 5 [make "c "Buzz]  if equal? 0 modulo :n 3 [make "c word "Fizz :c] output ifelse equal? :c " [:n] [:c]end repeat 100 [print fizzbuzz repcount]

Lhogho can use the above code, except that 'modulo' must be replaced with 'remainder'.

## LSE

1* FIZZBUZZ en L.S.E. 10 CHAINE FB20 FAIRE 45 POUR I_1 JUSQUA 100 30 FB_SI &MOD(I,3)=0 ALORS SI &MOD(I,5)=0 ALORS 'FIZZBUZZ' SINON 'FIZZ' SINON SI &MOD(I,5)=0 ALORS 'BUZZ' SINON ''40 AFFICHER[U,/] SI FB='' ALORS I SINON FB45*FIN BOUCLE50 TERMINER100 PROCEDURE &MOD(A,B) LOCAL A,B110 RESULTAT A-B*ENT(A/B)

## Lua

### If/else Ladder

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

### Concatenation

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 = i	end	print(output)end

### Quasi bit field

word = {"Fizz", "Buzz", "FizzBuzz"} for i = 1, 100 do        print(word[(i % 3 == 0 and 1 or 0) + (i % 5 == 0 and 2 or 0)] or i)end

### Lookup table

local t = {        [0]  = "FizzBuzz",        [3]  = "Fizz",        [5]  = "Buzz",        [6]  = "Fizz",        [9]  = "Fizz",        [10] = "Buzz",        [12] = "Fizz"} for i = 1, 100 do        print(t[i%15] or i)end

### Fast Version without Modulo

 #!/usr/bin/env luajitlocal to=arg[1] or tonumber(arg[1]) or 100local CF,CB=3,5local cf,cb=CF,CBfor i=1,to do	cf,cb=cf-1,cb-1	if cf~=0 and cb~=0 then		io.write(i)	else		if cf==0 then			cf=CF			io.write("Fizz")		end		if cb==0 then			cb=CB			io.write("Buzz")		end	end	io.write(", ")end
Output:
> ./fizzbuzz.lua
1, 2, Fizz, 4, Buzz, Fizz, 7, 8, Fizz, Buzz, 11, Fizz, 13, 14, FizzBuzz, 16, 17, Fizz, 19, Buzz, Fizz, 22, 23, Fizz, Buzz, 26, Fizz, 28, 29, FizzBuzz, 31, 32, Fizz, 34, Buzz, Fizz, 37, 38, Fizz, Buzz, 41, Fizz, 43, 44, FizzBuzz, 46, 47, Fizz, 49, Buzz, Fizz, 52, 53, Fizz, Buzz, 56, Fizz, 58, 59, FizzBuzz, 61, 62, Fizz, 64, Buzz, Fizz, 67, 68, Fizz, Buzz, 71, Fizz, 73, 74, FizzBuzz, 76, 77, Fizz, 79, Buzz, Fizz, 82, 83, Fizz, Buzz, 86, Fizz, 88, 89, FizzBuzz, 91, 92, Fizz, 94, Buzz, Fizz, 97, 98, Fizz, Buzz, %


## Luck

for i in range(1,101) do (   if i%15 == 0 then print("FizzBuzz")   else if i%3 == 0 then print("Fizz")   else if i%5 == 0 then print("Buzz")   else print(i))

## M2000 Interpreter

 \\ one line, hard to readFor i=1 to 100 {If i mod 3=0 Then {if i mod 5=0 Then Print "FizzBuzz"  Else Print "Fizz"} Else {if i mod 5=0 Then Print "Buzz" else print i } } \\ Better codeFor i=1 to 100 {      Push str$(i,0)+". "+if$(i mod 3=0->"Fizz","")+if$(i mod 5=0->"Buzz","") If stackitem$()="" then Drop : Continue      Print Letter$} \\ Far Better CodeFor i=1 to 100 { Printme(if$(i mod 3=0->"Fizz","")+if$(i mod 5=0->"Buzz","")) }Sub Printme(a$)      If a$<>"" Then Print a$ else Print iEnd Sub

## Maple

One line:

seq(print(if(modp(n,3)=0,if(modp(n,15)=0,"FizzBuzz","Fizz"),if(modp(n,5)=0,"Buzz",n))),n=1..100):

With a fizzbuzz function defined:

fizzbuzz1 := n->if(modp(n,3)=0,if(modp(n,15)=0,"FizzBuzz","Fizz"),if(modp(n,5)=0,"Buzz",n)):for i to 100 do fizzbuzz1(i); od;

Using piecewise:

fizzbuzz2 := n->piecewise(modp(n,15)=0,"FizzBuzz",modp(n,3)=0,"Fizz",modp(n,5)=0,"Buzz",n):for i to 100 do fizzbuzz2(i); od;

Using conventional if/then branches:

fizzbuzz3 := proc(n) local r;  r:=map2(modp,n,[3,5]);  if r=[0,0] then "FizzBuzz"  elif r[1]=0 then "Fizz"  elif r[2]=0 then "Buzz"  else n fi;end proc:for i to 100 do fizzbuzz3(i); od;

## Mathematica / Wolfram Language

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

Using rules,

fizz[i_] := Mod[i, 3] == 0buzz[i_] := Mod[i, 5] == 0Range[100] /. {i_ /; fizz[i]&&buzz[i] :> "FizzBuzz", \               i_?fizz :> "Fizz", i_?buzz :> "Buzz"}

Using rules, but different approach:

SetAttributes[f,Listable]f[n_ /; Mod[n, 15] == 0] := "FizzBuzz";f[n_ /; Mod[n, 3] == 0] := "Fizz";f[n_ /; Mod[n, 5] == 0] := "Buzz";f[n_] := n; f[Range[100]]

An extendible version using Table

Table[If[# === "", i, #]&@StringJoin[   Table[If[Divisible[i, [email protected]], [email protected], ""],          {nw, {{3, "Fizz"}, {5, "Buzz"}}}]],       {i, 1, 100}]

Another one-liner using Map (the /@ operator shorthand of it) and a pure function with a very readable Which

 Which[ Mod[#,15] == 0, "FizzBuzz", Mod[#, 3] == 0, "Fizz", Mod[#,5]==0, "Buzz",  True, #]& /@ Range[1,100] 

## MATLAB

There are more sophisticated solutions to this task, but in the spirit of "lowest level of comprehension required to illustrate adequacy" this is what one might expect from a novice programmer (with a little variation in how the strings are stored and displayed).

function fizzBuzz()     for i = (1:100)        if mod(i,15) == 0           fprintf('FizzBuzz ')        elseif mod(i,3) == 0           fprintf('Fizz ')        elseif mod(i,5) == 0           fprintf('Buzz ')        else           fprintf('%i ',i))         end    end    fprintf('\n');    end

Here's a more extendible version that uses disp() to print the output:

function out = fizzbuzzS()	nums = [3, 5];	words = {'fizz', 'buzz'};	for (n=1:100)		tempstr = '';		for (i = 1:2)			if mod(n,nums(i))==0				tempstr = [tempstr,  words{i}];			end		end		if length(tempstr) == 0 			disp(n);		else 			disp(tempstr);		end	endend

## Maxima

for n thru 100 do   if mod(n, 15) = 0 then disp("FizzBuzz")   elseif mod(n, 3) = 0 then disp("Fizz")   elseif mod(n,5) = 0 then disp("Buzz")   else disp(n);

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

## MontiLang

&DEFINE LOOP 100&1 VAR i . FOR LOOP    || VAR ln .    i 5 % 0 ==     IF : .        ln |Buzz| + VAR ln .    ENDIF    i 3 % 0 ==    IF : .        ln |Fizz| + VAR ln .    ENDIF    ln || ==    IF : .        i PRINT .    ENDIF    ln || !=    IF : .        ln PRINT .    ENDIFi 1 + VAR i .ENDFOR

## MoonScript

for i = 1,100    print ((a) -> a == "" and i or a) table.concat {        i % 3 == 0 and "Fizz" or ""        i % 5 == 0 and "Buzz" or ""}

FIZZBUZZ NEW I FOR I=1:1:100 WRITE !,$SELECT(('(I#3)&'(I#5)):"FizzBuzz",'(I#5):"Buzz",'(I#3):"Fizz",1:I) KILL I QUIT fizzbuzz for i=1:1:100 do write ! . write:(i#3)&(i#5) i write:'(i#3) "Fizz" write:'(i#5) "Buzz" ## Nanoquery for i in range(1, 100) if ((i % 3) = 0) and ((i % 5) = 0) println "FizzBuzz" else if i % 3 = 0 println "Fizz" else if i % 5 = 0 println "Buzz" else println i endend ## Neko var i = 1 while(i < 100) { if(i % 15 == 0) {$print("FizzBuzz\n");	} else if(i % 3 == 0) {		$print("Fizz\n"); } else if(i % 5 == 0) {$print("Buzz\n");	} else {		$print(i + "\n"); } i ++= 1} ## Nemerle The naive approach: using System;using System.Console; module FizzBuzz{ FizzBuzz(x : int) : string { |x when x % 15 == 0 => "FizzBuzz" |x when x % 5 == 0 => "Buzz" |x when x % 3 == 0 => "Fizz" |_ =>$"$x" } Main() : void { foreach (i in [1 .. 100]) WriteLine($"$(FizzBuzz(i))") }} A much slicker approach is posted here ## NetRexx loop j=1 for 100 select when j//15==0 then say 'FizzBuzz' when j//5==0 then say 'Buzz' when j//3==0 then say 'Fizz' otherwise say j.right(4) endend ## Never func fizz_buzz() -> int{ var i = 1; for (i = 1; i <= 100; i = i + 1) { /* if (i % 15 == 0) */ if (i % 3 == 0 && i % 5 == 0) { prints("Fizz Buzz\n") } else if (i % 3 == 0) { prints("Fizz\n") } else if (i % 5 == 0) { prints("Buzz\n") } else { prints(i + "\n") } }; 0} func main() -> int { fizz_buzz(); 0} Output: prompt$ never -f fizzbuzz.nev 2>/dev/null
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
Fizz Buzz
16
...
89
Fizz Buzz
91
92
Fizz
94
Buzz
Fizz
97
98
Fizz
Buzz

## NewLISP

(dotimes (i 100)  (println   (cond    ((= 0 (% i 15)) "FizzBuzz")    ((= 0 (% i 3)) "Fizz")    ((= 0 (% i 5)) "Buzz")    ('t i))))

## NewtonScript

for i := 1 to 100 dobegin	if i mod 15 = 0 then		print("FizzBuzz")	else if i mod 3 = 0 then		print("Fizz")	else if i mod 5 = 0 then		print("Buzz")	else		print(i);	print("\n")end

## Nickle

/* Fizzbuzz in nickle */ void function fizzbuzz(size) {    for (int i = 1; i < size; i++) {        if (i % 15 == 0) { printf("Fizzbuzz\n"); }        else if (i % 5 == 0) { printf("Buzz\n"); }        else if (i % 3 == 0) { printf("Fizz\n"); }        else { printf("%i\n", i); }    }} fizzbuzz(1000);

## Nim

Translation of: Python
for i in 1..100:  if i mod 15 == 0:    echo("FizzBuzz")  elif i mod 3 == 0:    echo("Fizz")  elif i mod 5 == 0:    echo("Buzz")  else:    echo(i)

## Oberon-2

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

## Objeck

bundle Default {  class Fizz {    function : Main(args : String[]) ~ Nil {      for(i := 0; i <= 100; i += 1;) {        if(i % 15 = 0) {          "FizzBuzz"->PrintLine();        }        else if(i % 3 = 0) {          "Fizz"->PrintLine();        }          else if(i % 5 = 0) {          "Buzz"->PrintLine();        }        else {          i->PrintLine();        };      };    }  }}

## Objective-C

// FizzBuzz in Objective-C#import <stdio.h> main() {	for (int i=1; i<=100; i++) {		if (i % 15 == 0) {		    printf("FizzBuzz\n");		} else if (i % 3 == 0) {		    printf("Fizz\n");		} else if (i % 5 == 0) {		    printf("Buzz\n");		} else {		    printf("%i\n", i);		}	}}

## OCaml

Idiomatic OCaml to solve the stated problem:

let fizzbuzz i =  match i mod 3, i mod 5 with    0, 0 -> "FizzBuzz"  | 0, _ -> "Fizz"  | _, 0 -> "Buzz"  | _    -> string_of_int i let _ =  for i = 1 to 100 do print_endline (fizzbuzz i) done

With a view toward extensibility, there are many approaches: monadic, list of rules, ... here we'll use a piped sequence of rules to define a new "fizzbuzz" function:

(* Useful rule declaration: "cond => f", 'cond'itionally applies 'f' to 'a'ccumulated value *)let (=>) cond f a = if cond then f a else alet append s a = a^s let fizzbuzz i =  "" |> (i mod 3 = 0 => append "Fizz")     |> (i mod 5 = 0 => append "Buzz")     |> (function "" -> string_of_int i                | s  -> s)

## 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")  else    disp(i)  endifendfor

## Oforth

: fizzbuzz| i |   100 loop: i [      null       i 3 mod ifZero: [ "Fizz" + ]      i 5 mod ifZero: [ "Buzz" + ]      dup ifNull: [ drop i ] .       ] ; 

## OOC

fizz: func (n: Int) -> Bool {  if(n % 3 == 0) {    printf("Fizz")    return true  }  return false} buzz: func (n: Int) -> Bool {  if(n % 5 == 0) {    printf("Buzz")    return true  }  return false} main: func {  for(n in 1..100) {    fizz:= fizz(n)    buzz:= buzz(n)    fizz || buzz || printf("%d", n)    println()  }}

## Order

#include <order/interpreter.h> // Get FB for one number#define ORDER_PP_DEF_8fizzbuzz ORDER_PP_FN(            \8fn(8N,                                                \    8let((8F, 8fn(8N, 8G,                              \                  8is_0(8remainder(8N, 8G)))),         \         8cond((8ap(8F, 8N, 15), 8quote(fizzbuzz))     \               (8ap(8F, 8N, 3), 8quote(fizz))          \               (8ap(8F, 8N, 5), 8quote(buzz))          \               (8else, 8N)))) ) // Print E followed by a comma (composable, 8print is not a function)#define ORDER_PP_DEF_8print_el ORDER_PP_FN( \8fn(8E, 8print(8E 8comma)) ) ORDER_PP(  // foreach instead of map, to print but return nothing  8seq_for_each(8compose(8print_el, 8fizzbuzz), 8seq_iota(1, 100)))

## Oz

declare  fun {FizzBuzz X}     if     X mod 15 == 0 then 'FizzBuzz'     elseif X mod  3 == 0 then 'Fizz'     elseif X mod  5 == 0 then 'Buzz'     else                      X     end  endin  for I in 1..100 do     {Show {FizzBuzz I}}  end

## PARI/GP

{for(n=1,100,  print(if(n%3,    if(n%5,      n    ,      "Buzz"    )  ,    if(n%5,      "Fizz"    ,      "FizzBuzz"    )  )))}

## Pascal

program fizzbuzz(output);var  i: integer;begin  for i := 1 to 100 do    if i mod 15 = 0 then      writeln('FizzBuzz')    else if i mod 3 = 0 then      writeln('Fizz')    else if i mod 5 = 0 then      writeln('Buzz')    else      writeln(i)end.

## PDP-8 Assembly

Works with: PAL-D

Runs on SimH, or any PDP-8 with an EAE

 /--------------------------------------------------------/THIS PROGRAM PRINTS THE INTEGERS FROM 1 TO 100 (INCL)./WITH THE FOLLOWING RESTRICTIONS:/  FOR MULTIPLES OF THREE, PRINT 'FIZZ'/  FOR MULTIPLES OF FIVE,  PRINT 'BUZZ'/  FOR MULTIPLES OF BOTH THREE AND FIVE, PRINT 'FIZZBUZZ'/-------------------------------------------------------- /--------------------------------------------------------/DEFINES/--------------------------------------------------------SWBA=7447               /EAE MODE A INSTRUCTIONDVI=7407                /EAE DIVIDE INSTRUCTIONAIX0=0010               /AUTO INDEX REGISTER 0CR=0215                 /CARRIAGE RETURNLF=0212                 /LINEFEEDEOT=0000                /END OF TEXT NULFIZMOD=0003             /CONSTANT DECIMAL 3 (FIZZ)BUZMOD=0005             /CONSTANT DECIMAL 5 (BUZZ)K10=0012                /CONSTANT DECIMAL 10 LAST=0144               /FIZZBUZZ THE NUMBERS 1..LAST                        /0144 OCTAL == 100 DECIMAL                        /CAN BE ANY FROM [0001...7777] /--------------------------------------------------------/FIZZBUZZ START=0200/--------------------------------------------------------        *200            /START IN MEMORY AT 0200 OCTALFZZBZZ, CLA             /CLEAR AC        TAD (-LAST-1    /LOAD CONSTANT -(LAST+1)        DCA CNTR        /SET UP MAIN COUNTER        TAD (-FIZMOD    /SET UP FIZZ COUNTER        DCA FIZCTR      /TO -3        TAD (-BUZMOD    /SET UP BUZZ COUNTER        DCA BUZCTR      /TO -5LOOP,   ISZ CNTR        /READY?        SKP             /NO: CONTINUE        JMP I [7600     /YES: RETURN TO OS/8, REPLACE BY                        /'HLT' IF NOT ON OS/8CHKFIZ, ISZ FIZCTR      /MULTIPLE OF 3?        JMP CHKBUZ      /NO: CONTINUE        TAD FIZSTR      /YES: LOAD ADDRESS OF 'FIZZ'        JMS STROUT      /PRINT IT TO TTY        TAD (-FIZMOD    /RELOAD THE        DCA FIZCTR      /MOD 3 COUNTERCHKBUZ, ISZ BUZCTR      /MULTIPLE OF 5?        JMP CHKNUM      /NO: CONTINUE        TAD BUZSTR      /YES: LOAD ADDRESS OF 'BUZZ'        JMS STROUT      /PRINT IT TO TTY        TAD (-BUZMOD    /RELOAD THE        DCA BUZCTR      /MOD 5 COUNTER        JMP NXTLIN      /PRINT NEWLINE AND CONTINUECHKNUM, TAD FIZCTR      /CHECK WHETHER MOD 3 COUNTER        TAD (FIZMOD     /IS RELOADED        SNA             /DID WE JUST PRINT 'FIZZ'?        JMP NXTLIN      /YES: PRINT NEWLINE AND CONTINUE        CLA             /ZERO THE ACNUM,    TAD CNTR        /LOAD THE MAIN NUMBER COUNTER        TAD (LAST+1     /OFFSET IT TO A POSITIVE VALUE        JMS NUMOUT      /PRINT IT TO THE TTYNXTLIN, TAD LINSTR      /LOAD THE ADDRESS OF THE NEWLINE        JMS STROUT      /PRINT IT TO TTY        JMP LOOP        /CONTINUE WITH THE NEXT NUMBERCNTR,   0               /MAIN COUNTERFIZCTR, 0               /FIZZ COUNTERBUZCTR, 0               /BUZZ COUNTER /--------------------------------------------------------/WRITE ASCII CHARACTER IN AC TO TTY/PRE : AC=ASCII CHARACTER/POST: AC=0/--------------------------------------------------------CHROUT, .-.        TLS             /SEND CHARACTER TO TTY        TSF             /IS TTY READY FOR NEXT CHARACTER?        JMP .-1         /NO TRY AGAIN        CLA             /AC=0        JMP I CHROUT    /RETURN /--------------------------------------------------------/WRITE NUL TERMINATED ASCII STRING TO TTY/PRE : AC=ADDRESS OF STRING MINUS 1/POST: AC=0/--------------------------------------------------------STROUT, .-.        DCA AIX0        /STORE POINTER IN AUTO INDEX 0STRLOP, TAD I AIX0      /GET NEXT CHARACTER FROM STRING        SNA             /SKIP IF NOT EOT        JMP I STROUT    /RETURN        JMS CHROUT      /PRINT CHARACTER        JMP STRLOP      /GO GET NEXT CHARACTER /--------------------------------------------------------/WRITE NUMBER IN AC TO TTY AS DECIMAL/PRE : AC=UNSIGNED NUMBER BETWEEN 0000 AND 7777/POST: AC=0/--------------------------------------------------------NUMOUT, .-.        SWBA            /SET EAE IN MODE A        MQL             /MQ=NUM; AC=0        TAD BUFFER      /LOAD END OF BUFFER        DCA BUFPTR      /IN BUFPTR        SKP             /NUM IS ALREADY IN MQNUMLOP, MQL             /MQ=NUM; AC=0        DVI             /MQ=NUM/10; AC=NUM-(NUM/10)*10        K10             /DECIMAL 10        TAD ("0         /ADD ASCII ZERO        DCA I BUFPTR    /STORE CHAR BUFFER, BACK TO FRONT        CMA             /AC=-1        TAD BUFPTR      /DECREMENT        DCA BUFPTR      /BUFFER POINTER        MQA             /MQ -> AC        SZA             /READY IF ZERO        JMP NUMLOP      /GET NEXT DIGIT        TAD BUFPTR      /LOAD START OF CONVERTED NUMBER        JMS STROUT      /SEND IT TO TTY        JMP I NUMOUT    /RETURNBUFFER, .+4             /ADDRESS OF BUFFER        *.+4            /RESERVE 4 LOCATIONS (MAX=4095)        EOT             /END OF BUFFERBUFPTR, 0               /POINTER IN BUFFER /--------------------------------------------------------/STRINGS/--------------------------------------------------------FIZSTR, .               /FIZZ STRING        "F; "I; "Z; "Z; EOTBUZSTR, .               /BUZZ STRING        "B; "U; "Z; "Z; EOTLINSTR, .               /NEWLINE STIRNG        CR; LF; EOT        $ Output: . .PAL FIZBUZ.PA ERRORS DETECTED: 0 LINKS GENERATED: 0 .LOAD FIZBUZ.BN .START 1 2 FIZZ 4 BUZZ FIZZ 7 8 FIZZ BUZZ 11 FIZZ 13 14 FIZZBUZZ 16 17 FIZZ 19 BUZZ FIZZ 22 23 FIZZ BUZZ 26 FIZZ 28 29 FIZZBUZZ 31 32 FIZZ 34 BUZZ FIZZ 37 38 FIZZ BUZZ 41 FIZZ 43 44 FIZZBUZZ 46 47 FIZZ 49 BUZZ FIZZ 52 53 FIZZ BUZZ 56 FIZZ 58 59 FIZZBUZZ 61 62 FIZZ 64 BUZZ FIZZ 67 68 FIZZ BUZZ 71 FIZZ 73 74 FIZZBUZZ 76 77 FIZZ 79 BUZZ FIZZ 82 83 FIZZ BUZZ 86 FIZZ 88 89 FIZZBUZZ 91 92 FIZZ 94 BUZZ FIZZ 97 98 FIZZ BUZZ .  ## Peloton Variable-length padded English dialect <# DEFINE USERDEFINEDROUTINE LITERAL>__FizzBuzz|<# SUPPRESSAUTOMATICWHITESPACE><# TEST ISITMODULUSZERO PARAMETER LITERAL>1|3</#><# TEST ISITMODULUSZERO PARAMETER LITERAL>1|5</#><# ONLYFIRSTOFLASTTWO><# SAY LITERAL>Fizz</#></#><# ONLYSECONDOFLASTTWO><# SAY LITERAL>Buzz</#></#><# BOTH><# SAY LITERAL>FizzBuzz</#></#><# NEITHER><# SAY PARAMETER>1</#></#></#></#><# ITERATE FORITERATION LITERAL LITERAL>100|<# ACT USERDEFINEDROUTINE POSITION FORITERATION>__FizzBuzz|...</#> </#> Fixed-length English dialect <@ DEFUDRLIT>__FizzBuzz|<@ SAW><@ TSTMD0PARLIT>1|3</@><@ TSTMD0PARLIT>1|5</@><@ O12><@ SAYLIT>Fizz</@></@><@ O22><@ SAYLIT>Buzz</@></@><@ BTH><@ SAYLIT>FizzBuzz</@></@><@ NTH><@ SAYPAR>1</@></@></@></@><@ ITEFORLITLIT>100|<@ ACTUDRPOSFOR>__FizzBuzz|...</@> </@> ## Perl  use strict;use warnings;use feature qw(say); for my$i (1..100) {    say $i % 15 == 0 ? "FizzBuzz" :$i %  3 == 0 ? "Fizz"      : $i % 5 == 0 ? "Buzz" :$i;}

More concisely:

print 'Fizz'x!($_ % 3) . 'Buzz'x!($_ % 5) || $_, "\n" for 1 .. 100; For code-golfing: print+(Fizz)[$_%3].(Buzz)[$_%5]||$_,$/for 1..1e2 For array of values: map((Fizz)[$_%3].(Buzz)[$_%5]||$_,1..100);

Cheating:

### 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.

## PicoLisp

We could simply use 'at' here:

(for N 100   (prinl      (or (pack (at (0 . 3) "Fizz") (at (0 . 5) "Buzz")) N) ) ) # Above, we simply count till 100 'prin'-ting number 'at' 3rd ('Fizz'), 5th ('Buzz') and 'pack'-ing 15th number ('FizzBuzz').# Rest of the times 'N' is printed as it loops in 'for'.  

Or do it the standard way:

(for N 100   (prinl      (cond         ((=0 (% N 15)) "FizzBuzz")         ((=0 (% N 3)) "Fizz")         ((=0 (% N 5)) "Buzz")         (T N) ) ) )

## 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");      }   }}

## PILOT

C  :i = 0*loopC  :i = i + 1J ( i > 100 )    : *finishedC  :modulo = i % 15J ( modulo = 0 ) : *fizzbuzzC  :modulo = i % 3J ( modulo = 0 ) : *fizzC  :modulo = i % 5J ( modulo = 0 ) : *buzzT  :#iJ  : *loop*fizzbuzzT  :FizzBuzzJ  : *loop*fizzT  :FizzJ  : *loop*buzzT  :BuzzJ  : *loop*finishedEND:

## PIR

Works with: Parrot version tested with 2.4.0
.sub main :main  .local int f  .local int mf  .local int skipnum  f = 1LOOP:   if f > 100 goto DONE  skipnum = 0  mf = f % 3  if mf == 0 goto FIZZFIZZRET:  mf = f % 5  if mf == 0 goto BUZZBUZZRET:  if skipnum > 0 goto SKIPNUM  print fSKIPNUM:  print "\n"  inc f   goto LOOP  endFIZZ:  print "Fizz"  inc skipnum  goto FIZZRET  endBUZZ:  print "Buzz"  inc skipnum  goto BUZZRET  endDONE:  end.end

## PL/I

do i = 1 to 100;   select;      when (mod(i,15) = 0) put skip list ('FizzBuzz');      when (mod(i,3)  = 0) put skip list ('Fizz');      when (mod(i,5)  = 0) put skip list ('Buzz');      otherwise put skip list (i);   end;end;

## PL/SQL

BEGIN  FOR i IN 1 .. 100  LOOP    CASE    WHEN MOD(i, 15) = 0 THEN      DBMS_OUTPUT.put_line('FizzBuzz');    WHEN MOD(i, 5) = 0 THEN      DBMS_OUTPUT.put_line('Buzz');    WHEN MOD(i, 3) = 0 THEN      DBMS_OUTPUT.put_line('Fizz');    ELSE      DBMS_OUTPUT.put_line(i);    END CASE;  END LOOP;END;

## Pony

use "collections" actor Main  new create(env: Env) =>    for i in Range[I32](1, 100) do      env.out.print(fizzbuzz(i))    end   fun fizzbuzz(n: I32): String =>    if (n % 15) == 0 then      "FizzBuzz"    elseif (n % 5) == 0 then      "Buzz"    elseif (n % 3) == 0 then      "Fizz"    else      n.string()    end

## 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 { 	/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

or...

/fizzdict 100 dict deffizzdict 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} def1 1 100 { mod3 } for 1 1 100 { mod5 } for 1 1 100 { mod15} for1 1 100 { dup currentdict exch known { currentdict exch get}{notmod} ifelse print (\n) print} forend

## Potion

 1 to 100 (a):  if (a % 15 == 0):    'FizzBuzz'.  elsif (a % 3 == 0):    'Fizz'.  elsif (a % 5 == 0):    'Buzz'.  else: a. string print  "\n" print.

## PowerShell

### Concatenation

Translation of: C#

## Processing

### Console & Visualization

Reserved variable "width" in Processing is 100 pixels by default, suitable for this FizzBuzz exercise. Accordingly, range is pixel index from 0 to 99.

for (int i = 0; i < width; i++) {  if (i % 3 == 0 && i % 5 == 0) {    stroke(255, 255, 0);    println("FizzBuzz!");  }  else if (i % 5 == 0) {    stroke(0, 255, 0);    println("Buzz");  }  else if (i % 3 == 0) {    stroke(255, 0, 0);    println("Fizz");  }  else {    stroke(0, 0, 255);    println(i);  }   line(i, 0, i, height);}

### Console & Visualization, Ternary

for (int i = 0; i < width; i++) {  stroke((i % 5 == 0 && i % 3 == 0) ? #FFFF00 : (i % 5 == 0) ? #00FF00 : (i % 3 == 0) ? #FF0000 : #0000FF);  line(i, 0, i, height);  println((i % 5 == 0 && i % 3 == 0) ? "FizzBuzz!" : (i % 5 == 0) ? "Buzz" : (i % 3 == 0) ? "Fizz" : i);}

### Console

for (int i = 1; i <= 100; i++) {  if (i % 3 == 0) {    print("Fizz");  }  if (i % 5 == 0) {    print("Buzz");  }  if (i % 3 != 0 && i % 5 != 0) {    print(i);  }  print("\n");}

### Console, "Futureproof"

for(int i = 1; i <= 100; i++){  String output = "";   if(i % 3 == 0) output += "Fizz";  if(i % 5 == 0) output += "Buzz";  // copy & paste above line to add more tests   if(output == "") output = str(i);  println(output);}

All examples produce the same console output:

Output:
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz
Fizz
22
23
Fizz
Buzz
26
Fizz
28
29
FizzBuzz
31
32
Fizz
34
Buzz
Fizz
37
38
Fizz
Buzz
41
Fizz
43
44
FizzBuzz
46
47
Fizz
49
Buzz
Fizz
52
53
Fizz
Buzz
56
Fizz
58
59
FizzBuzz
61
62
Fizz
64
Buzz
Fizz
67
68
Fizz
Buzz
71
Fizz
73
74
FizzBuzz
76
77
Fizz
79
Buzz
Fizz
82
83
Fizz
Buzz
86
Fizz
88
89
FizzBuzz
91
92
Fizz
94
Buzz
Fizz
97
98
Fizz
Buzz


## 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.

fizzbuzz :-        foreach(between(1, 100, X), print_item(X)). print_item(X) :-        (  0 is X mod 15        -> print('FizzBuzz')        ;  0 is X mod 3        -> print('Fizz')        ;  0 is X mod 5        -> print('Buzz')        ;  print(X)        ),        nl.

More conventional:

fizzbuzz(X) :- 0 is X mod 15, write('FizzBuzz').fizzbuzz(X) :- 0 is X mod 3, write('Fizz').fizzbuzz(X) :- 0 is X mod 5, write('Buzz').fizzbuzz(X) :- write(X). dofizzbuzz :- foreach(between(1, 100, X), (fizzbuzz(X),nl)).

Clearer:

%        N  /3?  /5?  Vfizzbuzz(_, yes, yes, 'FizzBuzz').fizzbuzz(_, yes, no,  'Fizz').fizzbuzz(_, no,  yes, 'Buzz').fizzbuzz(N, no,  no,  N). % Unifies V with 'yes' if D divides evenly into N, 'no' otherwise.divisible_by(N, D, V) :-  ( 0 is N mod D -> V = yes  ;                 V = no). % Print 'Fizz', 'Buzz', 'FizzBuzz' or N as appropriate.fizz_buzz_or_n(N) :-  divisible_by(N, 3, Fizz),  divisible_by(N, 5, Buzz),  fizzbuzz(N, Fizz, Buzz, FB),  format("~p -> ~p~n", [N, FB]). main :-  foreach(between(1,100, N), fizz_buzz_or_n(N)).

## Pyret

fun fizzbuzz(n :: NumPositive) -> String:  doc: For positive input which is multiples of three return 'Fizz', for the multiples of five return 'Buzz'.   For numbers which are multiples of both three and five return 'FizzBuzz'. Otherwise, return the number itself.  ask:    | num-modulo(n, 15) == 0 then: "FizzBuzz"    | num-modulo(n, 3) == 0 then: "Fizz"    | num-modulo(n, 5) == 0 then: "Buzz"    | otherwise: num-to-string(n)  endwhere:  fizzbuzz(1) is "1"  fizzbuzz(101) is "101"  fizzbuzz(45) is "FizzBuzz"  fizzbuzz(33) is "Fizz"  fizzbuzz(25) is "Buzz"end range(1, 101).map(fizzbuzz).each(print)

## Python

### Python2: Simple

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

### Python3: Simple

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

### Python: Simple - no duplication

for n in range(1,101):    response = ''     if not n%3:        response += 'Fizz'    if not n%5:        response += 'Buzz'     print(response or n) 

One liner using string concatenation:

for i in range(1,101): print("Fizz"*(i%3==0) + "Buzz"*(i%5==0) or i)

One liner another code:

for i in range(100):print(i%3//2*'Fizz'+i%5//4*'Buzz'or i+1)

List Comprehensions:

 for n in range(1, 100):    fb = ''.join([ denom[1] if n % denom[0] == 0 else '' for denom in [(3,'fizz'),(5,'buzz')] ])    print fb if fb else n 

Another list comprehension:

 print (', '.join([(x%3<1)*'Fizz'+(x%5<1)*'Buzz' or str(x) for x in range(1,101)]))   

### Python: List Comprehension (Python 3)

[print("FizzBuzz") if i % 15 == 0 else print("Fizz") if i % 3 == 0 else print("Buzz") if i % 5 == 0 else print(i) for i in range(1,101)]

### Python: Lazily

You can also create a lazy, unbounded sequence by using generator expressions:

from itertools import cycle, izip, count, islice fizzes = cycle([""] * 2 + ["Fizz"])buzzes = cycle([""] * 4 + ["Buzz"])both = (f + b for f, b in izip(fizzes, buzzes)) # if the string is "", yield the number# otherwise yield the stringfizzbuzz = (word or n for word, n in izip(both, count(1))) # print the first 100for i in islice(fizzbuzz, 100):    print i

Or equivalently, in terms of map, and Python 3 libraries:

Works with: Python version 3.7
'''Fizz buzz''' from itertools import count, cycle, islice  # fizzBuzz :: () -> Generator [String]def fizzBuzz():    '''A non-finite stream of fizzbuzz terms.'''    return map(        lambda f, b, n: (f + b) or n,        cycle([''] * 2 + ['Fizz']),        cycle([''] * 4 + ['Buzz']),        map(str, count(1))    )  # main :: IO ()def main():    '''Display of first 100 terms of the fizzbuzz series.    '''    print(unlines(        take(100)(            fizzBuzz()        )    ))  # GENERIC ------------------------------------------------- # take :: Int -> [a] -> [a]# take :: Int -> String -> Stringdef take(n):    '''The prefix of xs of length n,       or xs itself if n > length xs.    '''    return lambda xs: (        xs[0:n]        if isinstance(xs, (list, tuple))        else list(islice(xs, n))    )  # unlines :: [String] -> Stringdef unlines(xs):    '''A single string formed by the intercalation       of a list of strings with the newline character.    '''    return '\n'.join(xs)  if __name__ == '__main__':    main()

### Python3.8: With walrus operator

print(*map(lambda n: 'Fizzbuzz '[(i):i+13] if (i := n**4%-15) > -14 else n, range(1,100)))

### Python: Math tricks

Numbers ending in 5 or 0 are divisible by 5. Numbers whose digits recursively summed to a single-digit number == 3,6 or 9 are divisible by 3.

 def numsum(n):	''' The recursive sum of all digits in a number         unit a single character is obtained'''	res = sum([int(i) for i in str(n)])	if res < 10: return res	else : return numsum(res) for n in range(1,101):	response = 'Fizz'*(numsum(n) in [3,6,9]) + \                   'Buzz'*(str(n)[-1] in ['5','0'])\	            or n	print(response) 

## Q

 {$[0=x mod 15;"FizzBuzz";0=x mod 5;"Buzz";0=x mod 3;"Fizz";string x]} each 1+til 15 Or to print the result:  -1 "\n" sv{$[0=x mod 15;"FizzBuzz";0=x mod 5;"Buzz";0=x mod 3;"Fizz";string x]} each 1+til 15;

## R

xx <- x <- 1:100xx[x %% 3 == 0] <- "Fizz"xx[x %% 5 == 0] <- "Buzz"xx[x %% 15 == 0] <- "FizzBuzz"xx

Or, without directly checking for divisibility by 15:

xx <- rep("", 100)x <- 1:100xx[x %% 3 == 0] <- paste0(xx[x %% 3 == 0], "Fizz")xx[x %% 5 == 0] <- paste0(xx[x %% 5 == 0], "Buzz")xx[xx == ""] <- x[xx == ""]xx

Or, (ab)using the vector recycling rule:

x <- paste(rep("", 100), c("", "", "Fizz"), c("", "", "", "", "Buzz"), sep="")cat(ifelse(x == "", 1:100, x), "\n")

Or, with a more straightforward use of ifelse:

x <- 1:100ifelse(x %% 15 == 0, 'FizzBuzz',       ifelse(x %% 5 == 0, 'Buzz',              ifelse(x %% 3 == 0, 'Fizz', x)))

## Racket

#lang racket (for ([n (in-range 1 101)])   (displayln    (match (gcd n 15)      [15 "fizzbuzz"]      [3 "fizz"]      [5 "buzz"]      [_ n])))

## Raku

(formerly Perl 6)

Works with: Rakudo Star version 2015-09-10

Most straightforwardly:

for 1 .. 100 {    when $_ %% (3 & 5) { say 'FizzBuzz'; } when$_ %% 3       { say 'Fizz'; }    when $_ %% 5 { say 'Buzz'; } default { .say; }} Or abusing multi subs: multi sub fizzbuzz(Int$ where * %% 15) { 'FizzBuzz' }multi sub fizzbuzz(Int $where * %% 5) { 'Buzz' }multi sub fizzbuzz(Int$ where * %%  3) { 'Fizz' }multi sub fizzbuzz(Int $number ) {$number }(1 .. 100)».&fizzbuzz.say;

Or abusing list metaoperators:

[1..100].map({[~] ($_%%3,$_%%5) »||» "" Z&& <fizz buzz> or $_ })».say Concisely (readable): say 'Fizz' x$_ %% 3 ~ 'Buzz' x $_ %% 5 ||$_ for 1 .. 100;

Shortest FizzBuzz to date:

## Rascal

import IO; public void fizzbuzz() {   for(int n <- [1 .. 100]){      fb = ((n % 3 == 0) ? "Fizz" : "") + ((n % 5 == 0) ? "Buzz" : "");      println((fb == "") ?"<n>" : fb);   }}

## 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

## ReasonML

 let fizzbuzz i =>  switch (i mod 3, i mod 5) {  | (0, 0) => "FizzBuzz"  | (0, _) => "Fizz"  | (_, 0) => "Buzz"  | _ => string_of_int i  }; for i in 1 to 100 {  print_endline (fizzbuzz i)}; 

## REBOL

An implementation that concatenates strings and includes a proper code header (title, date, etc.)

rebol [	Title: "FizzBuzz"	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]

Here is an example by Nick Antonaccio.

repeat i 100 [    print switch/default 0 compose [        (mod i 15) ["fizzbuzz"]        (mod i 3)  ["fizz"]        (mod i 5)  ["buzz"]    ][i]]

And a minimized version:

repeat i 100[j:""if i // 3 = 0[j:"fizz"]if i // 5 = 0[j: join j"buzz"]if""= j[j: i]print j]

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]

## Retro

This is a port of some Forth code.

: fizz?    ( s-f ) 3 mod 0 = ;: buzz?    ( s-f ) 5 mod 0 = ;: num?     ( s-f ) dup fizz? swap buzz? or 0 = ;: ?fizz    ( s-  ) fizz? [ "Fizz" puts ] ifTrue ;: ?buzz    ( s-  ) buzz? [ "Buzz" puts ] ifTrue ;: ?num     ( s-  ) num? &putn &drop if ;: fizzbuzz ( s-  ) dup ?fizz dup ?buzz dup ?num space ;: all      (  -  ) 100 [ 1+ fizzbuzz ] iter ;

It's cleaner to use quotes and combinators though:

needs math': <fizzbuzz>  [ 15 ^math'divisor? ] [ drop "FizzBuzz" puts ] when  [  3 ^math'divisor? ] [ drop "Fizz"     puts ] when  [  5 ^math'divisor? ] [ drop "Buzz"     puts ] when putn ;: fizzbuzz cr 100 [ 1+ <fizzbuzz> space ] iter ;

## REXX

This version's program logic closely mirrors the problem statement:

### three IF-THEN

/*REXX program displays numbers  1 ──► 100  (some transformed) for the FizzBuzz problem.*/                                                 /*╔═══════════════════════════════════╗*/  do j=1  to 100;      z=  j                     /*║                                   ║*/  if j//3    ==0  then z= 'Fizz'                 /*║  The divisors  (//)  of the  IFs  ║*/  if j//5    ==0  then z= 'Buzz'                 /*║  must be in ascending order.      ║*/  if j//(3*5)==0  then z= 'FizzBuzz'             /*║                                   ║*/  say right(z, 8)                                /*╚═══════════════════════════════════╝*/  end   /*j*/                                    /*stick a fork in it,  we're all done. */

output

       1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz
Fizz
22
23
Fizz
Buzz
26
Fizz
28
29
FizzBuzz
31
32
Fizz
34
Buzz
Fizz
37
38
Fizz
Buzz
41
Fizz
43
44
FizzBuzz
46
47
Fizz
49
Buzz
Fizz
52
53
Fizz
Buzz
56
Fizz
58
59
FizzBuzz
61
62
Fizz
64
Buzz
Fizz
67
68
Fizz
Buzz
71
Fizz
73
74
FizzBuzz
76
77
Fizz
79
Buzz
Fizz
82
83
Fizz
Buzz
86
Fizz
88
89
FizzBuzz
91
92
Fizz
94
Buzz
Fizz
97
98
Fizz
Buzz


### SELECT-WHEN

This version is a different form, but essentially identical to the   IF-THEN   (above),
but doesn't require the use of a temporary variable to hold/contain the output.

/*REXX program displays numbers  1 ──► 100  (some transformed) for the FizzBuzz problem.*/                                                 /*╔═══════════════════════════════════╗*/  do j=1  to 100                                 /*║                                   ║*/      select                                     /*║                                   ║*/      when j//15==0  then say 'FizzBuzz'         /*║ The divisors  (//)  of the  WHENs ║*/      when j//5 ==0  then say '    Buzz'         /*║ must be in  descending  order.    ║*/      when j//3 ==0  then say '    Fizz'         /*║                                   ║*/      otherwise           say right(j, 8)        /*╚═══════════════════════════════════╝*/      end   /*select*/  end       /*j*/                                /*stick a fork in it,  we're all done. */

output   is identical to the 1st REXX version.

### two IF-THEN

This version lends itself to expansion   (such as using   Jazz   for multiples of   7).

/*REXX program displays numbers  1 ──► 100  (some transformed) for the FizzBuzz problem.*/    do j=1  for 100;  _=   if j//3 ==0  then _=_'Fizz'   if j//5 ==0  then _=_'Buzz'/* if j//7 ==0  then _=_'Jazz' */                /* ◄─── note that this is a comment.   */   say right(word(_ j,1),8)   end   /*j*/                                   /*stick a fork in it,  we're all done. */

output   is identical to the 1st REXX version.

### "geek" version

/*REXX program displays numbers  1 ──► 100  (some transformed) for the FizzBuzz problem.*/                                                 /* [↓]  concise, but somewhat obtuse.  */  do j=1  for 100  say right(word(word('Fizz', 1+(j//3\==0))word('Buzz', 1+(j//5\==0)) j, 1), 8)  end   /*j*/                                                 /*stick a fork in it,  we're all done. */

output   is identical to the 1st REXX version.

## Ring

 for n = 1 to 100    if n % 15 = 0 see "" + n + " = " + "FizzBuzz"+ nl    but n % 5 = 0 see "" + n + " = " + "Buzz" + nl    but n % 3 = 0 see "" + n + " = " + "Fizz" + nl    else see "" + n + " = " + n + nl oknext 

## Robotic

 set "local1" to 1: "loop"wait for 10if "('local1' % 15)" = 0 then "fizzbuzz"if "('local1' % 3)" = 0 then "fizz"if "('local1' % 5)" = 0 then "buzz"* "&local1&": "inc"inc "local1" by 1if "local1" <= 100 then "loop"goto "done" : "fizzbuzz"* "FizzBuzz"goto "inc" : "fizz"* "Fizz"goto "inc" : "buzz"* "Buzz"goto "inc" : "done"end 

The wait for 10 function is not really necessary, but it helps to slow down the output.

## Rockstar

Midnight takes your heart and your soul
While your heart is as high as your soul
Put your heart without your soul into your heart

Give back your heart

Desire is a lovestruck ladykiller
My world is nothing
Fire is ice
Hate is water
Until my world is Desire,
Build my world up
If Midnight taking my world, Fire is nothing and Midnight taking my world, Hate is nothing
Shout "FizzBuzz!"
Take it to the top

If Midnight taking my world, Fire is nothing
Shout "Fizz!"
Take it to the top

If Midnight taking my world, Hate is nothing
Say "Buzz!"
Take it to the top

Whisper my world


## 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)  putsend

A bit more straightforward:

(1..100).each do |n|  puts if (n % 15).zero?    "FizzBuzz"  elsif (n % 5).zero?    "Buzz"  elsif (n % 3).zero?    "Fizz"  else    n  endend

Enumerable#Lazy and classes:

We can grab the first n fizz/buzz/fizzbuzz numbers in a list with a user defined function (filter_map), starting at the number we desire

i.e, grabbing the first 10 fizz numbers starting from 30, fizz = Fizz.new(30,10) #=> [30, 33, 36, 39, 42, 45, 48, 51, 54, 57]

 class Enumerator::Lazy  def filter_map    Lazy.new(self) do |holder, *values|      result = yield *values      holder << result if result    end  endend class Fizz  def initialize(head, tail)    @list = (head..Float::INFINITY).lazy.filter_map{|i| i if i % 3 == 0}.first(tail)  end   def fizz?(num)    search = @list    search.include?(num)  end   def drop(num)    list = @list    list.delete(num)  end   def to_a    @list.to_a  endend class Buzz  def initialize(head, tail)    @list = (head..Float::INFINITY).lazy.filter_map{|i| i if i % 5 == 0}.first(tail)  end   def buzz?(num)    search = @list    search.include?(num)  end   def drop(num)    list = @list    list.delete(num)  end   def to_a    @list.to_a  endend class FizzBuzz  def initialize(head, tail)    @list = (head..Float::INFINITY).lazy.filter_map{|i| i if i % 15 == 0}.first(tail)  end   def fizzbuzz?(num)    search = @list    search.include?(num)  end   def to_a    @list.to_a  end   def drop(num)    list = @list    list.delete(num)  endendstopper = 100@fizz = Fizz.new(1,100)@buzz = Buzz.new(1,100)@fizzbuzz = FizzBuzz.new(1,100)def min(v, n)  if v == 1    puts "Fizz: #{n}"    @fizz::drop(n)  elsif v == 2    puts "Buzz: #{n}"    @buzz::drop(n)  else    puts "FizzBuzz: #{n}"    @fizzbuzz::drop(n)  endend(@fizz.to_a & @fizzbuzz.to_a).map{|d| @fizz::drop(d)}(@buzz.to_a & @fizzbuzz.to_a).map{|d| @buzz::drop(d)}while @fizz.to_a.min < stopper or @buzz.to_a.min < stopper or @fizzbuzz.to_a.min < stopper  f, b, fb = @fizz.to_a.min, @buzz.to_a.min, @fizzbuzz.to_a.min  min(1,f)  if f < fb and f < b  min(2,b)  if b < f and b < fb  min(0,fb) if fb < b and fb < fend

An example using string interpolation:

(1..100).each do |n|  v = "#{"Fizz" if n % 3 == 0}#{"Buzz" if n % 5 == 0}"  puts v.empty? ? n : vend

Interpolation inspired one-liner:

1.upto(100) { |n| puts "#{'Fizz' if n % 3 == 0}#{'Buzz' if n % 5 == 0}#{n if n % 3 != 0 && n % 5 != 0}" }

An example using append:

1.upto 100 do |n|  r = ''  r << 'Fizz' if n % 3 == 0  r << 'Buzz' if n % 5 == 0  r << n.to_s if r.empty?  puts rend

Yet another solution:

1.upto(100) { |i| puts "#{[:Fizz][i%3]}#{[:Buzz][i%5]}"[/.+/] || i }

Yet another solution:

1.upto(100){|i|puts'FizzBuzz '[n=i**4%-15,n+13]||i}

Used Enumerable#cycle:

f = [nil, nil, :Fizz].cycleb = [nil, nil, nil, nil, :Buzz].cycle(1..100).each do |i|  puts "#{f.next}#{b.next}"[/.+/] || iend

After beforehand preparing the Array which put the number from 1 to 100, it processes.

seq = *0..100{Fizz:3, Buzz:5, FizzBuzz:15}.each{|k,n| n.step(100,n){|i|seq[i]=k}}puts seq.drop(1)

Monkeypatch example:

class Integer  def fizzbuzz    v = "#{"Fizz" if self % 3 == 0}#{"Buzz" if self % 5 == 0}"    v.empty? ? self : v  endend puts *(1..100).map(&:fizzbuzz)

Without mutable variables or inline printing.

fizzbuzz = ->(i) do  (i%15).zero? and next "FizzBuzz"  (i%3).zero?  and next "Fizz"  (i%5).zero?  and next "Buzz"  iend puts (1..100).map(&fizzbuzz).join("\n")

Jump anywhere#Ruby has a worse example of FizzBuzz, using a continuation!

## Ruby with RSpec

This is a solution to FizzBuzz using Test-Driven Development (In this case, with Ruby and RSpec). You will need to set up the correct file structure first, with /lib and /spec directories in your root.

Your spec/fizzbuzz_spec.rb file should like this:

 require 'fizzbuzz' describe 'FizzBuzz' do  context 'knows that a number is divisible by' do    it '3' do      expect(is_divisible_by_three?(3)).to be_true    end    it '5' do      expect(is_divisible_by_five?(5)).to be_true    end    it '15' do      expect(is_divisible_by_fifteen?(15)).to be_true    end  end  context 'knows that a number is not divisible by' do    it '3' do      expect(is_divisible_by_three?(1)).not_to be_true    end    it '5' do      expect(is_divisible_by_five?(1)).not_to be_true    end    it '15' do      expect(is_divisible_by_fifteen?(1)).not_to be_true    end  end  context 'while playing the game it returns' do    it 'the number' do      expect(fizzbuzz(1)).to eq 1    end    it 'Fizz' do      expect(fizzbuzz(3)).to eq 'Fizz'    end    it 'Buzz' do      expect(fizzbuzz(5)).to eq 'Buzz'    end    it 'FizzBuzz' do      expect(fizzbuzz(15)).to eq 'FizzBuzz'    end  endend 

There are many ways to get these tests to pass. Here is an example solution of what your lib/fizzbuzz.rb file could look like:

 def fizzbuzz(number)  return 'FizzBuzz' if is_divisible_by_fifteen?(number)  return 'Buzz' if is_divisible_by_five?(number)  return 'Fizz' if is_divisible_by_three?(number)  numberend def is_divisible_by_three?(number)  is_divisible_by(number, 3)end def is_divisible_by_five?(number)  is_divisible_by(number, 5)end def is_divisible_by_fifteen?(number)  is_divisible_by(number, 15)end def is_divisible_by(number, divisor)  number % divisor == 0end  

When writing Test Driven code, it's important to remember that you should use the Red, Green, Refactor cycle. Simply writing each of these code snippets independently would go against everything TDD is about. Here is a good video that takes you through the process of writing this FizzBuzz implementation using Ruby & RSpec.

## Rust

A version using an iterator and immutable data:

use std::borrow::Cow; // Allows us to avoid unnecessary allocationsfn main() {    (1..101).map(|n| match (n % 3, n % 5) {        (0, 0) => "FizzBuzz".into(),        (0, _) => "Fizz".into(),        (_, 0) => "Buzz".into(),        _ => Cow::from(n.to_string())    }).for_each(|n| println!("{}", n));} 

Or a version unwrapping the iterator into a loop:

 use std::borrow::Cow;fn main() {    for i in 1..101 {        println!("{}", match (i % 3, i % 5) {            (0, 0) => "FizzBuzz".into(),            (0, _) => "Fizz".into(),            (_, 0) => "Buzz".into(),            _ => Cow::from(i.to_string()),        });    }}

Or the ultimate optimized version with hardcoded output, no standard library or main function, and direct assembly syscalls to write to stdout.

#![no_std]#![feature(asm, lang_items, libc, no_std, start)] extern crate libc; const LEN: usize = 413;static OUT: [u8; LEN] = *b"\    1\n2\nFizz\n4\nBuzz\nFizz\n7\n8\nFizz\nBuzz\n11\nFizz\n13\n14\nFizzBuzz\n\    16\n17\nFizz\n19\nBuzz\nFizz\n22\n23\nFizz\nBuzz\n26\nFizz\n28\n29\nFizzBuzz\n\    31\n32\nFizz\n34\nBuzz\nFizz\n37\n38\nFizz\nBuzz\n41\nFizz\n43\n44\nFizzBuzz\n\    46\n47\nFizz\n49\nBuzz\nFizz\n52\n53\nFizz\nBuzz\n56\nFizz\n58\n59\nFizzBuzz\n\    61\n62\nFizz\n64\nBuzz\nFizz\n67\n68\nFizz\nBuzz\n71\nFizz\n73\n74\nFizzBuzz\n\    76\n77\nFizz\n79\nBuzz\nFizz\n82\n83\nFizz\nBuzz\n86\nFizz\n88\n89\nFizzBuzz\n\    91\n92\nFizz\n94\nBuzz\nFizz\n97\n98\nFizz\nBuzz\n"; #[start]fn start(_argc: isize, _argv: *const *const u8) -> isize {    unsafe {        asm!(            "            mov $$1, %rax mov$$1, %rdi            mov $0, %rsi mov$1, %rdx            syscall            "            :            : "r" (&OUT[0]) "r" (LEN)            : "rax", "rdi", "rsi", "rdx"            :        );    }    0} #[lang = "eh_personality"] extern fn eh_personality() {}#[lang = "panic_fmt"] extern fn panic_fmt() {}

A folding iterator version, buffered with a single string allocation, by making use of expressions the write! macro.

use std::fmt::Write; fn fizzbuzz() -> String {    (1..101).fold(String::new(), |mut output, x| {        let fizz = if x % 3 == 0 { "fizz" } else { "" };        let buzz = if x % 5 == 0 { "buzz" } else { "" };        if fizz.len() + buzz.len() != 0 {            output + fizz + buzz + "\n"        } else {            write!(&mut output, "{}", x).unwrap();            output + "\n"        }    })} fn main() {    println!("{}", fizzbuzz());}

## Salmon

iterate (x; [1...100])  ((x % 15 == 0) ? "FizzBuzz" :   ((x % 3 == 0) ? "Fizz" :    ((x % 5 == 0) ? "Buzz" : x)))!;

or

iterate (x; [1...100])  {    if (x % 15 == 0)        "FizzBuzz"!    else if (x % 3 == 0)        "Fizz"!    else if (x % 5 == 0)        "Buzz"!    else        x!;  };

## SAS

data _null_;  do i=1 to 100;    if mod(i,15)=0 then put "FizzBuzz";    else if mod(i,5)=0 then put "Buzz";    else if mod(i,3)=0 then put "Fizz";    else put i;  end;run;

## Sather

class MAIN is  main is    loop i ::= 1.upto!(100);      s:STR := "";      if i % 3 = 0 then s := "Fizz"; end;      if i % 5 = 0 then s := s + "Buzz"; end;      if s.length > 0 then        #OUT + s + "\n";      else        #OUT + i + "\n";      end;          end;  end;end;

## Scala

Library: Scala

### Idiomatic scala code

object FizzBuzz extends App {  1 to 100 foreach { n =>    println((n % 3, n % 5) match {      case (0, 0) => "FizzBuzz"      case (0, _) => "Fizz"      case (_, 0) => "Buzz"      case _ => n    })  }}

### Geeky over-generalized solution ☺

def replaceMultiples(x: Int, rs: (Int, String)*): Either[Int, String] =  rs map { case (n, s) => Either cond(x % n == 0, s, x)} reduceLeft ((a, b) =>     a fold(_ => b, s => b fold(_ => a, t => Right(s + t)))) def fizzbuzz = replaceMultiples(_: Int, 3 -> "Fizz", 5 -> "Buzz") fold(_.toString, identity) 1 to 100 map fizzbuzz foreach println

### By a two-liners geek

def f(n: Int, div: Int, met: String, notMet: String): String = if (n % div == 0) met else notMetfor (i <- 1 to 100) println(f(i, 15, "FizzBuzz", f(i, 3, "Fizz", f(i, 5, "Buzz", i.toString))))

### One-liner geek

for (i <- 1 to 100) println(Seq(15 -> "FizzBuzz", 3 -> "Fizz", 5 -> "Buzz").find(i % _._1 == 0).map(_._2).getOrElse(i))

### Functional Scala

def fizzbuzz(l: List[String], n: Int, s: String) = if (l.head.toInt % n == 0) l :+ s else ldef fizz(l: List[String]) = fizzbuzz(l, 3, "Fizz")def buzz(l: List[String]) = fizzbuzz(l, 5, "Buzz")def headOrTail(l: List[String]) = if (l.tail.size == 0) l.head else l.tail.mkStringStream.from(1).take(100).map(n => List(n.toString)).map(fizz).map(buzz).map(headOrTail).foreach(println)

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

Using a recursive procedure.

(define (fizzbuzz x y)  (println    (cond (( = (modulo x 15) 0 ) "FizzBuzz")          (( = (modulo x 3) 0 ) "Fizz")          (( = (modulo x 5) 0 ) "Buzz")          (else x)))     (if (< x y) (fizzbuzz (+ x 1) y))) (fizzbuzz 1 100)

## Sed

#n# doesn't work if there's no input# initialize counters (0 = empty) and values/.*/  0/: loop# increment counters, set carrys/^$$a*$$ $$b*$$ $$[0-9][0-9]*$$/\1a \2b \[email protected]/# propagate carry: carrys/ @/ 1/s/[email protected]/@0/s/[email protected]/9/s/[email protected]/8/s/[email protected]/7/s/[email protected]/6/s/[email protected]/5/s/[email protected]/4/s/[email protected]/3/s/[email protected]/2/s/[email protected]/1//@/b carry# save stateh# handle factorss/aaa/Fizz/s/bbbbb/Buzz/# strip value if any factor/z/s/[0-9]//g# strip counters and spacess/[ab ]//g# outputp# restore stateg# roll over counterss/aaa//s/bbbbb//# loop until value = 100/100/qb loop

Using seq:

 seq 100 | sed '/.*[05]$/s//Buzz/;n;s//Buzz/;n;s//Buzz/;s/^[0-9]*/Fizz/'  ### GNU sed GNU sed has first~step address expression that matches every stepth line. This makes following one-liners possible. Using seq:  seq 100 | sed '0~3 s/.*/Fizz/; 0~5 s/[0-9]*$/Buzz/' 

Using yes:

 yes | sed -n '0~3s/y/Fizz/;0~5s/y*$/Buzz/;tx;=;b;:x;p;100q'  Using the option -z (--zero-data) first introduced in GNU sed 4.2.2 (2012-12-22):  sed -nz '0~3s/^/Fizz/;0~5s/$/Buzz/;tx;=;b;:x;p;100q' /dev/zero | sed 'y/\[email protected]/\n/' 

Second invocation of sed translates null characters to newlines. The same could be achieved with tr \\0 \\n

 templates fizz  $mod 3 -> # <=0> 'Fizz' !end fizz templates buzz$ mod 5 -> #  <=0> 'Buzz' !end buzz [ 1..100 -> '$->fizz;$->buzz;' ] -> \[i](<''> $i ! <>$ !\)... -> '$;' -> !OUT::write  ## 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

The following example shows Tcl's substitution mechanism that allows to concatenate the results of two successive commands into a string:

## UNIX Shell

This solution should work with any Bourne-compatible shell:

i=1while expr $i '<=' 100 >/dev/null; do w=false expr$i % 3 = 0 >/dev/null && { printf Fizz; w=true; }	expr $i % 5 = 0 >/dev/null && { printf Buzz; w=true; } if$w; then echo; else echo $i; fi i=expr$i + 1done

### Versions for specific shells

The other solutions work with fewer shells.

The next solution requires $(( )) arithmetic expansion, and it should work with every POSIX shell. n=1while [ 100 -ge n ]; do if [$((n % 15)) -eq 0 ]; then    echo FizzBuzz  elif [ $((n % 3)) -eq 0 ]; then echo Fizz elif [$((n % 5)) -eq 0 ]; then    echo Buzz  else    echo $n fi n=$((n + 1))done

The next solution requires the (( )) command from the Korn Shell.

Works with: pdksh version 5.2.14
NUM=1until ((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 A version using concatenation: Works with: bash version 3 for ((n=1; n<=100; n++))do fb='' [$(( n % 3 )) -eq 0 ] && fb="${fb}Fizz" [$(( n % 5 )) -eq 0 ] && fb="${fb}Buzz" [ -n "${fb}" ] && echo "${fb}" || echo "$n"done

A version using some of the insane overkill of Bash 4:

Works with: bash version 4
command_not_found_handle () {   local Fizz=3 Buzz=5  [ $(($2 % $1 )) -eq 0 ] && echo -n$1 && [ ${!1} -eq 3 ]} for i in {1..100}do Fizz$i && ! Buzz $i || echo -n$i  echodone

Bash one-liner:

for i in {1..100};do ((($i%15==0))&& echo FizzBuzz)||((($i%5==0))&& echo Buzz;)||((($i%3==0))&& echo Fizz;)||echo$i;done

### C Shell

@ n = 1while ( $n <= 100 ) if ($n % 15 == 0) then    echo FizzBuzz  else if ($n % 5 == 0) then echo Buzz else if ($n % 3 == 0) then    echo Fizz  else    echo $n endif @ n += 1end ## Ursa ## fizzbuzz#decl int ifor (set i 1) (< i 101) (inc i) if (= (mod i 3) 0) out "fizz" console end if if (= (mod i 5) 0) out "buzz" console end if if (not (or (= (mod i 3) 0) (= (mod i 5) 0))) out i console end if out endl consoleend for ## Ursala #import std#import nat fizzbuzz = ^T(&&'Fizz'! not remainder\3,&&'Buzz'! not remainder\5)|| ~&h+ %nP #show+ main = fizzbuzz*t iota 101 ## V [fizzbuzz 1 [>=] [ [[15 % zero?] ['fizzbuzz' puts] [5 % zero?] ['buzz' puts] [3 % zero?] ['fizz' puts] [true] [dup puts] ] when succ ] while]. |100 fizzbuzz ### Second try (a compiler for fizzbuzz) define a command that will generate a sequence [seq [] swap dup [zero? not] [rolldown [dup] dip cons rollup pred] while pop pop]. create a quote that will return a quote that returns a quote if its argument is an integer (A HOF) [check [N X F : [[integer?] [[X % zero?] [N F cons] if] if]] view]. Create a quote that will make sure that the above quote is applied correctly if given (Number Function) as arguments. [func [[N F] : [dup N F check i] ] view map]. And apply it 100 seq [ [15 [pop 'fizzbuzz' puts]] [5 [pop 'buzz' puts]] [3 [pop 'fizz' puts]] [1 [puts]]] [func dup] step [i true] map pop the first one is much better :) ## Vala int main() { for (int i = 1; i <= 100; i++) { if (i % 3 == 0) stdout.printf("Fizz\n"); if (i % 5 == 0) stdout.printf("Buzz\n"); if (i % 15 == 0) stdout.printf("FizzBuzz\n"); if (i % 3 != 0 && i % 5 != 0) stdout.printf("%d\n", i); }return 0;;} ## VAX Assembly  00000008 0000 1 len =8 00000008 0000 2 msg: .blkb len ;output buffer 0000000C 0008 3 desc: .blkl 1 ;descriptor lenght field 00000000' 000C 4 .address msg ;pointer to buffer 00000012 0010 5 outlen: .blkw 1 4C 55 21 0000001A'010E0000' 0012 6 ctr: .ascid "!UL" 001D 7 0000 001D 8 .entry start,0 52 7C 001F 9 clrq r2 ;r2+r3 64bit 52 D6 0021 10 incl r2 ;start index 1 0023 11 loop: E2 AF B4 0023 12 clrw desc ;assume not fizz and or buzz 55 D7 AF 9E 0026 13 movab msg, r5 ;pointer to message buffer 54 50 52 03 7B 002A 14 ediv #3,r2,r0,r4 ;divr.rl,divd.rq,quo.wl,rem.wl 54 D5 002F 15 tstl r4 ;remainder 0B 12 0031 16 bneq not_fizz ;not equal zero 0033 17 85 7A7A6966 8F D0 0033 18 movl #^a"fizz", (r5)+ ;add to message CA AF 04 A0 003A 19 addw2 #4, desc ;and update length 003E 20 not_fizz: 54 50 52 05 7B 003E 21 ediv #5,r2,r0,r4 54 D5 0043 22 tstl r4 0B 12 0045 23 bneq not_buzz 0047 24 85 7A7A7562 8F D0 0047 25 movl #^a"buzz", (r5)+ B6 AF 04 A0 004E 26 addw2 #4, desc 0052 27 not_buzz: B3 AF B5 0052 28 tstw desc ;fizz and or buzz? 1B 12 0055 29 bneq show_buffer ;neq - yes 0057 30 AD AF 08 B0 0057 31 movw #len, desc ;fao length limit 005B 32$fao_s -			;eql -no                                     005B    33 		 ctrstr = ctr, -	;show number                                     005B    34 		 outlen = outlen, -                                     005B    35 		 outbuf = desc, -                                     005B    36 		 p1     = r2                 96 AF   A0 AF   B0  006D    37 	movw	outlen, desc		;characters filled by fao                                     0072    38 show_buffer:                         93 AF   7F  0072    39 	pushaq	desc              00000000'GF   01   FB  0075    40 	calls	#1, g^lib$put_output 9F 52 00000064 8F F3 007C 41 AOBLEQ #100,r2,loop ;limit.rl, index.ml 04 0084 42 ret 0085 43 .end start ## VBA  Option Explicit Sub FizzBuzz()Dim Tb(1 To 100) As VariantDim i As Integer For i = 1 To 100 Tb(i) = i If i Mod 15 = 0 Then Tb(i) = "FizzBuzz" ElseIf i Mod 5 = 0 Then Tb(i) = "Buzz" ElseIf i Mod 3 = 0 Then Tb(i) = "Fizz" End If Next Debug.Print Join(Tb, vbCrLf)End Sub As an alternative, testing each number only once:  Sub FizzBuzz() Dim i As Integer Dim T(1 To 99) As Variant For i = 1 To 99 Step 3 T(i + 0) = IIf((i + 0) Mod 5 = 0, "Buzz", i) T(i + 1) = IIf((i + 1) Mod 5 = 0, "Buzz", i + 1) T(i + 2) = IIf((i + 2) Mod 5 = 0, "FizzBuzz", "Fizz") Next i Debug.Print Join(T, ", ") & ", Buzz"End Sub  ## VBScript Works with: Windows Script Host version * For i = 1 To 100 If i Mod 15 = 0 Then WScript.Echo "FizzBuzz" ElseIf i Mod 5 = 0 Then WScript.Echo "Buzz" ElseIf i Mod 3 = 0 Then WScript.Echo "Fizz" Else WScript.Echo i End IfNext ##### An Alternative Works with: Windows Script Host version * With WScript.StdOut For i = 1 To 100 If i Mod 3 = 0 Then .Write "Fizz" If i Mod 5 = 0 Then .Write "Buzz" If .Column = 1 Then .WriteLine i Else .WriteLine "" NextEnd With ## Verbexx @LOOP init:{@VAR t3 t5; @VAR i = 1} while:(i <= 100) next:{i++}{ t3 = (i % 3 == 0); t5 = (i % 5 == 0); @SAY ( @CASE when:(t3 && t5) { 'FizzBuzz } when: t3 { 'Fizz } when: t5 { 'Buzz } else: { i } );}; ## VHDL entity fizzbuzz isend entity fizzbuzz; architecture beh of fizzbuzz is procedure fizzbuzz(num : natural) is begin if num mod 15 = 0 then report "FIZZBUZZ"; elsif num mod 3 = 0 then report "FIZZ"; elsif num mod 5 = 0 then report "BUZZ"; else report to_string(num); end if; end procedure fizzbuzz; begin p_fizz : process is begin for i in 1 to 100 loop fizzbuzz(i); end loop; wait for 200 us; end process p_fizz; end architecture beh; ## Vim Script for i in range(1, 100) if i % 15 == 0 echo "FizzBuzz" elseif i % 5 == 0 echo "Buzz" elseif i % 3 == 0 echo "Fizz" else echo i endifendfor ## Visual Basic .NET ## Visual Prolog  implement main open core, console class predicates fizzbuzz : (integer) -> string procedure (i). clauses fizzbuzz(X) = S :- X mod 15 = 0, S = "FizzBuzz", !. fizzbuzz(X) = S :- X mod 5 = 0, S = "Buzz", !. fizzbuzz(X) = S :- X mod 3 = 0, S = "Fizz", !. fizzbuzz(X) = S :- S = toString(X). run() :- foreach X = std::fromTo(1,100) do write(fizzbuzz(X)), write("\n") end foreach, succeed. end implement main goal console::runUtf8(main::run).  ## Vlang fn fizzbuzz(n int) { for i := 0; i < n; i++ { if i % 15 == 0 { println('FizzBuzz') } else if i % 3 == 0 { println('Fizz') } else if i % 5 == 0 { println('Buzz') } else { println(i) } }} fn main() { fizzbuzz(50)} Output: FizzBuzz 1 2 Fizz 4 Buzz ... 11 Fizz 13 14 FizzBuzz  ## Wart for i 1 (i <= 100) ++i prn (if (divides i 15) "FizzBuzz" (divides i 3) "Fizz" (divides i 5) "Buzz" :else i) ## WDTE let io => import 'io';let s => import 'stream'; let multiple of n => == (% n of) 0; let fizzbuzz n => switch n { multiple (* 3 5) => 'FizzBuzz'; multiple 3 => 'Fizz'; multiple 5 => 'Buzz'; default => n;} -- io.writeln io.stdout; s.range 1 101 -> s.map fizzbuzz -> s.drain; ## Whitespace ## Wortel @each &x!console.log x !*&x?{%%x 15 "FizzBuzz" %%x 5 "Buzz" %%x 3 "Fizz" x} @to 100 ## X86 Assembly  ; x86_64 linux nasm section .bssnumber resb 4 section .datafizz: db "Fizz"buzz: db "Buzz"newLine: db 10 section .textglobal _start _start: mov rax, 1 ; initialize counter loop: push rax call fizzBuzz pop rax inc rax cmp rax, 100 jle loop mov rax, 60 mov rdi, 0 syscall fizzBuzz: mov r10, rax mov r15, 0 ; boolean fizz or buzz checkFizz: xor rdx, rdx ; clear rdx for division mov rbx, 3 div rbx cmp rdx, 0 ; modulo result here jne checkBuzz mov r15, 1 mov rsi, fizz mov rdx, 4 mov rax, 1 mov rdi, 1 syscall checkBuzz: mov rax, r10 xor rdx, rdx mov rbx, 5 div rbx cmp rdx, 0 jne finishLine mov r15, 1 mov rsi, buzz mov rdx, 4 mov rax, 1 mov rdi, 1 syscall finishLine: ; print number if no fizz or buzz cmp r15, 1 je nextLine mov rax, r10 call printNum ret nextLine: mov rsi, newLine mov rdx, 1 mov rax, 1 mov rdi, 1 syscall ret printNum: ; write proper digits into number buffer cmp rax, 100 jl lessThanHundred mov byte [number], 49 mov byte [number + 1], 48 mov byte [number + 2], 48 mov rdx, 3 jmp print lessThanHundred: ; get digits to write through division xor rdx, rdx mov rbx, 10 div rbx add rdx, 48 cmp rax, 0 je lessThanTen add rax, 48 mov byte [number], al mov byte [number + 1], dl mov rdx, 2 jmp print lessThanTen: mov byte [number], dl mov rdx, 1 print: mov byte [number + rdx], 10 ; add newline inc rdx mov rax, 1 mov rdi, 1 mov rsi, number syscall ret  ## XLISP (defun fizzbuzz () (defun fizzb (x y) (display (cond ((= (mod x 3) (mod x 5) 0) "FizzBuzz") ((= (mod x 3) 0) "Fizz") ((= (mod x 5) 0) "Buzz") (t x))) (newline) (if (< x y) (fizzb (+ x 1) y))) (fizzb 1 100)) (fizzbuzz) ## XMIDAS startmacro loop 100 count calc/quiet three ^count 3 modulo calc/quiet five ^count 5 modulo if ^three eq 0 and ^five eq 0 say "fizzbuzz" elseif ^three eq 0 say "fizz" elseif ^five eq 0 say "buzz" else say ^count endif endloopendmacro ## Xojo  For i As Integer = 1 To 100 If i Mod 3 = 0 And i Mod 5 = 0 Then Print("FizzBuzz") ElseIf i Mod 3 = 0 Then Print("Fizz") ElseIf i Mod 5 = 0 Then Print("Buzz") Else Print(Str(i)) End If Next An alternative syntax:  For i As Integer = 1 To 100 Select Case True Case i Mod 3 = 0 And i Mod 5 = 0 Print("FizzBuzz") Case i Mod 3 = 0 Print("Fizz") Case i Mod 5 = 0 Print("Buzz") Else Print(Str(i)) End Select Next ## XPath 2.0 for$n in 1 to 100 return    concat('fizz'[not($n mod 3)], 'buzz'[not($n mod 5)], $n[$n mod 15 = (1,2,4,7,8,11,13,14)])

...or alternatively...

for $n in 1 to 100 return ($n, 'Fizz', 'Buzz', 'FizzBuzz')[number(($n mod 3) = 0) + number(($n mod 5) = 0)*2 + 1]

## XPL0

code CrLf=9, IntOut=11, Text=12;int     N;[for N:= 1 to 100 do       [if rem(N/3)=0 then Text(0,"Fizz");        if rem(N/5)=0 then Text(0,"Buzz")        else if rem(N/3)#0 then IntOut(0,N);        CrLf(0);       ];]
Output:
1
2
Fizz
4
Buzz
Fizz
7
...
89
FizzBuzz
91
92
Fizz
94
Buzz
Fizz
97
98
Fizz
Buzz


## XSLT

### XSLT 1.0

Works with: xsltproc version libxslt 10126

## Yorick

### Iterative solution

for(i = 1; i <= 100; i++) {    if(i % 3 == 0)        write, format="%s", "Fizz";    if(i % 5 == 0)        write, format="%s", "Buzz";    if(i % 3 && i % 5)        write, format="%d", i;    write, "";}

### Vectorized solution

output = swrite(format="%d", indgen(100));output(3::3) = "Fizz";output(5::5) = "Buzz";output(15::15) = "FizzBuzz";write, format="%s\n", output;

## zkl

foreach n in ([1..100]) {   if(n % 3 == 0) print("Fizz");   if(not (n%5)) "Buzz".print();   if(n%3 and n%5) print(n);   println();}

Or, using infinite lazy sequences:

fcn f(a,b,c){ a+b and a+b or c }Walker.cycle("","","Fizz").zipWith(f,Walker.cycle("","","","","Buzz"),[1..])   .walk(100).concat("\n").println();

More of the same:

Walker.cycle(0,0,"Fizz",0,"Buzz","Fizz",0,0,"Fizz","Buzz",0,"Fizz",0,0,"FizzBuzz")   .zipWith(fcn(a,b){ a or b },[1..]).walk(100).concat("\n").println();
Output:
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
...


## ZX Spectrum Basic

Translation of: Applesoft BASIC
10 DEF FN m(a,b)=a-INT (a/b)*b20 FOR a=1 TO 10030 LET o$=""40 IF FN m(a,3)=0 THEN LET o$="Fizz"50 IF FN m(a,5)=0 THEN LET o$=o$+"Buzz"60 IF o$="" THEN LET o$=STR$a70 PRINT o$80 NEXT a