I'm working on modernizing Rosetta Code's infrastructure. Starting with communications. Please accept this time-limited open invite to RC's Slack.. --Michael Mol (talk) 20:59, 30 May 2020 (UTC)

# FizzBuzz

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

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 until i > 100                                          let fizz = cond #( when i mod 3 = 0 then |fizz| else space )                                              buzz = cond #( when i mod 5 = 0 then |buzz| else space )                                              fb   = |{ fizz }{ buzz }| in                                         ( switch #( fb when space then i else fb ) ) ) ).

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

### TDD using delegates

using System;using System.Collections;using System.Collections.Generic;using System.Globalization;using System.Linq;using Microsoft.VisualStudio.TestTools.UnitTesting; namespace FizzBuzz{    [TestClass]    public class FizzBuzzTest    {        private FizzBuzz fizzBuzzer;         [TestInitialize]        public void Initialize()        {            fizzBuzzer = new FizzBuzz();        }         [TestMethod]        public void Give4WillReturn4()        {            Assert.AreEqual("4", fizzBuzzer.FizzBuzzer(4));        }         [TestMethod]        public void Give9WillReturnFizz()        {            Assert.AreEqual("Fizz", fizzBuzzer.FizzBuzzer(9));        }         [TestMethod]        public void Give25WillReturnBuzz()        {            Assert.AreEqual("Buzz", fizzBuzzer.FizzBuzzer(25));        }         [TestMethod]        public void Give30WillReturnFizzBuzz()        {            Assert.AreEqual("FizzBuzz", fizzBuzzer.FizzBuzzer(30));        }         [TestMethod]        public void First15()        {            ICollection expected = new ArrayList                {"1", "2", "Fizz", "4", "Buzz", "Fizz", "7", "8", "Fizz", "Buzz", "11", "Fizz", "13", "14", "FizzBuzz"};             var actual = Enumerable.Range(1, 15).Select(x => fizzBuzzer.FizzBuzzer(x)).ToList();             CollectionAssert.AreEqual(expected, actual);        }         [TestMethod]        public void From1To100_ToShowHowToGet100()        {            const int expected = 100;            var actual = Enumerable.Range(1, 100).Select(x => fizzBuzzer.FizzBuzzer(x)).ToList();             Assert.AreEqual(expected, actual.Count);        }    }     public class FizzBuzz    {        private delegate string Xzzer(int value);        private readonly IList<Xzzer> _functions = new List<Xzzer>();         public FizzBuzz()        {            _functions.Add(x => x % 3 == 0 ? "Fizz" : "");            _functions.Add(x => x % 5 == 0 ? "Buzz" : "");        }         public string FizzBuzzer(int value)        {            var result = _functions.Aggregate(String.Empty, (current, function) => current + function.Invoke(value));            return String.IsNullOrEmpty(result) ? value.ToString(CultureInfo.InvariantCulture) : result;        }    }}

### Good old C ways

using System;int max = 100;for(int i=0;    ++i<=max;     Console.WriteLine("{0}{1}{2}", i%3==0 ? "Fizz" : "", i%5==0 ? "Buzz" : "", i%3!=0 && i%5!=0  ? i.ToString() : "")){} 

## C++

### minimal conditions

#include <iostream>#include <chrono> int main(){ 	int fizz = 0, buzz = 0, fizzbuzz = 0; 	bool isFizz = false; 	auto startTime = std::chrono::high_resolution_clock::now(); 	for (unsigned int i = 1; i <= 4000000000; i++) {		isFizz = false; 		if (i % 3 == 0) {			isFizz = true;			fizz++;		} 		if (i % 5 == 0) {			if (isFizz) {				fizz--;				fizzbuzz++;			}			else {				buzz++;			}		} 	} 	auto endTime = std::chrono::high_resolution_clock::now();	auto totalTime = endTime - startTime; 	printf("\t fizz : %d, buzz: %d, fizzbuzz: %d, duration %lld milliseconds\n", fizz, buzz, fizzbuzz, (totalTime / std::chrono::milliseconds(1))); 	return 0;} 

### with modulo

#include <iostream> using namespace std;int main (){       for (int i = 1; i <= 100; i++)        {               if ((i % 15) == 0)                       cout << "FizzBuzz\n";               else if ((i % 3) == 0)                       cout << "Fizz\n";               else if ((i % 5) == 0)                       cout << "Buzz\n";               else                       cout << i << "\n";       }       return 0;}

### without modulo 15

#include <iostream>using namespace std; int main(){  for (int i = 0; i <= 100; ++i)  {    bool fizz = (i % 3) == 0;    bool buzz = (i % 5) == 0;    if (fizz)      cout << "Fizz";    if (buzz)      cout << "Buzz";    if (!fizz && !buzz)      cout << i;    cout << "\n";  }  return 0;}

### without modulo

Modulo can be expensive on some architectures.

#include <iostream> int main(){    int i, f = 2, b = 4;      for ( i = 1 ; i <= 100 ; ++i, --f, --b )    {        if ( f && b ) { std::cout << i;             }        if ( !f )     { std::cout << "Fizz"; f = 3; }        if ( !b )     { std::cout << "Buzz"; b = 5; }        std::cout << std::endl;    }     return 0;} 

### using std::transform

Works with: C++11
#include <iostream>                                                                                                     #include <algorithm>#include <vector> int main(){  std::vector<int> range(100);  std::iota(range.begin(), range.end(), 1);   std::vector<std::string> values;  values.resize(range.size());   auto fizzbuzz = [](int i) -> std::string {    if ((i%15) == 0) return "FizzBuzz";    if ((i%5) == 0)  return "Buzz";    if ((i%3) == 0)  return "Fizz";    return std::to_string(i);  };   std::transform(range.begin(), range.end(), values.begin(), fizzbuzz);   for (auto& str: values) std::cout << str << std::endl;   return 0;}

### metaprogramming

Version computing FizzBuzz at compile time with metaprogramming:

#include <iostream> template <int n, int m3, int m5> struct fizzbuzz : fizzbuzz<n-1, (n-1)%3, (n-1)%5>{  fizzbuzz()   { std::cout << n << std::endl; }}; template <int n>struct fizzbuzz<n, 0, 0> : fizzbuzz<n-1, (n-1)%3, (n-1)%5>{  fizzbuzz()   { std::cout << "FizzBuzz" << std::endl; }}; template <int n, int p>struct fizzbuzz<n, 0, p> : fizzbuzz<n-1, (n-1)%3, (n-1)%5>{  fizzbuzz()   { std::cout << "Fizz" << std::endl; }}; template <int n, int p>struct fizzbuzz<n, p, 0> : fizzbuzz<n-1, (n-1)%3, (n-1)%5>{  fizzbuzz()   { std::cout << "Buzz" << std::endl; }}; template <>struct fizzbuzz<0,0,0>{  fizzbuzz()   { std::cout << 0 << std::endl; }}; template <int n>struct fb_run{  fizzbuzz<n, n%3, n%5> fb;}; int main(){  fb_run<100> fb;  return 0;}

### hardcore templates

Compile with -ftemplate-depth-9000 -std=c++0x:

#include <iostream>#include <string>#include <cstdlib>#include <boost/mpl/string.hpp>#include <boost/mpl/fold.hpp>#include <boost/mpl/size_t.hpp> using namespace std;using namespace boost; ///////////////////////////////////////////////////////////////////////////////// exponentiation calculationstemplate <int accum, int base, int exp> struct POWER_CORE : POWER_CORE<accum * base, base, exp - 1>{}; template <int accum, int base>struct POWER_CORE<accum, base, 0>{    enum : int { val = accum };}; template <int base, int exp> struct POWER : POWER_CORE<1, base, exp>{}; ///////////////////////////////////////////////////////////////////////////////// # of digit calculationstemplate <int depth, unsigned int i> struct NUM_DIGITS_CORE : NUM_DIGITS_CORE<depth + 1, i / 10>{}; template <int depth>struct NUM_DIGITS_CORE<depth, 0>{    enum : int { val = depth};}; template <int i> struct NUM_DIGITS : NUM_DIGITS_CORE<0, i>{}; template <>struct NUM_DIGITS<0>{    enum : int { val = 1 };}; ///////////////////////////////////////////////////////////////////////////////// Convert digit to character (1 -> '1')template <int i>struct DIGIT_TO_CHAR{    enum : char{ val = i + 48 };}; ///////////////////////////////////////////////////////////////////////////////// Find the digit at a given offset into a number of the form 0000000017template <unsigned int i, int place> // place -> [0 .. 10]struct DIGIT_AT{    enum : char{ val = (i / POWER<10, place>::val) % 10 };}; struct NULL_CHAR{    enum : char{ val = '\0' };}; ///////////////////////////////////////////////////////////////////////////////// Convert the digit at a given offset into a number of the form '0000000017' to a charactertemplate <unsigned int i, int place> // place -> [0 .. 9]    struct ALT_CHAR : DIGIT_TO_CHAR< DIGIT_AT<i, place>::val >{}; ///////////////////////////////////////////////////////////////////////////////// Convert the digit at a given offset into a number of the form '17' to a character // Template description, with specialization to generate null characters for out of range offsetstemplate <unsigned int i, int offset, int numDigits, bool inRange>      struct OFFSET_CHAR_CORE_CHECKED{};template <unsigned int i, int offset, int numDigits>                    struct OFFSET_CHAR_CORE_CHECKED<i, offset, numDigits, false> : NULL_CHAR{};template <unsigned int i, int offset, int numDigits>                    struct OFFSET_CHAR_CORE_CHECKED<i, offset, numDigits, true>  : ALT_CHAR<i, (numDigits - offset) - 1 >{}; // Perform the range check and pass it ontemplate <unsigned int i, int offset, int numDigits>    struct OFFSET_CHAR_CORE : OFFSET_CHAR_CORE_CHECKED<i, offset, numDigits, offset < numDigits>{}; // Calc the number of digits and pass it ontemplate <unsigned int i, int offset>    struct OFFSET_CHAR : OFFSET_CHAR_CORE<i, offset, NUM_DIGITS<i>::val>{}; ///////////////////////////////////////////////////////////////////////////////// Integer to char* template. Works on unsigned ints.template <unsigned int i>struct IntToStr{    const static char str[];    typedef typename mpl::string<    OFFSET_CHAR<i, 0>::val,    OFFSET_CHAR<i, 1>::val,    OFFSET_CHAR<i, 2>::val,    OFFSET_CHAR<i, 3>::val,    OFFSET_CHAR<i, 4>::val,    OFFSET_CHAR<i, 5>::val,    /*OFFSET_CHAR<i, 6>::val,    OFFSET_CHAR<i, 7>::val,    OFFSET_CHAR<i, 8>::val,    OFFSET_CHAR<i, 9>::val,*/    NULL_CHAR::val>::type type;}; template <unsigned int i>const char IntToStr<i>::str[] = {    OFFSET_CHAR<i, 0>::val,    OFFSET_CHAR<i, 1>::val,    OFFSET_CHAR<i, 2>::val,    OFFSET_CHAR<i, 3>::val,    OFFSET_CHAR<i, 4>::val,    OFFSET_CHAR<i, 5>::val,    OFFSET_CHAR<i, 6>::val,    OFFSET_CHAR<i, 7>::val,    OFFSET_CHAR<i, 8>::val,    OFFSET_CHAR<i, 9>::val,    NULL_CHAR::val}; template <bool condition, class Then, class Else>struct IF{    typedef Then RET;}; template <class Then, class Else>struct IF<false, Then, Else>{    typedef Else RET;};  template < typename Str1, typename Str2 >struct concat : mpl::insert_range<Str1, typename mpl::end<Str1>::type, Str2> {};template <typename Str1, typename Str2, typename Str3 >struct concat3 : mpl::insert_range<Str1, typename mpl::end<Str1>::type, typename concat<Str2, Str3 >::type > {}; typedef typename mpl::string<'f','i','z','z'>::type fizz;typedef typename mpl::string<'b','u','z','z'>::type buzz;typedef typename mpl::string<'\r', '\n'>::type mpendl;typedef typename concat<fizz, buzz>::type fizzbuzz; // discovered boost mpl limitation on some length template <int N>struct FizzBuzz{    typedef typename concat3<typename FizzBuzz<N - 1>::type, typename IF<N % 15 == 0, typename fizzbuzz::type, typename IF<N % 3 == 0, typename fizz::type, typename IF<N % 5 == 0, typename buzz::type, typename IntToStr<N>::type >::RET >::RET >::RET, typename mpendl::type>::type type;}; template <>struct FizzBuzz<1>{    typedef mpl::string<'1','\r','\n'>::type type;}; int main(int argc, char** argv){    const int n = 7;    std::cout << mpl::c_str<FizzBuzz<n>::type>::value << std::endl;	return 0;}

Note: it takes up lots of memory and takes several seconds to compile. To enable compilation for 7 < n <= 25, please, modify include/boost/mpl/limits/string.hpp BOOST_MPL_LIMIT_STRING_SIZE to 128 instead of 32).

## Cduce

(* FizzBuzz in CDuce *) let format (n : Int) : Latin1 =    if (n mod 3 = 0) || (n mod 5 = 0) then "FizzBuzz"    else if (n mod 5 = 0) then "Buzz"    else if (n mod 3 = 0) then "Fizz"    else string_of (n);; let fizz (n : Int, size : Int) : _ =     print (format (n) @ "\n");    if (n = size) then        n = 0 (* do nothing *)    else        fizz(n + 1, size);; let fizbuzz (size : Int) : _ = fizz (1, size);; let _ = fizbuzz(100);;

## Ceylon

shared void run() => {for (i in 1..100) {for (j->k in [3->"Fizz", 5->"Buzz"]) if (j.divides(i)) k}.reduce(plus) else i}.each(print);

## Chapel

proc fizzbuzz(n) {	for i in 1..n do		if i % 15 == 0 then			writeln("FizzBuzz");		else if i % 5 == 0 then			writeln("Buzz");		else if i % 3 == 0 then			writeln("Fizz");		else			writeln(i);} fizzbuzz(100);

## Clay

main() {    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 print(i);    }}

## Clipper

Also compiles with Harbour (Harbour 3.2.0dev (r1405201749))

PROCEDURE Main()    LOCAL n   LOCAL cFB     FOR n := 1 TO 100      cFB := ""      AEval( { { 3, "Fizz" }, { 5, "Buzz" } }, {|x| cFB += iif( ( n % x[ 1 ] ) == 0, x[ 2 ], "" ) } )      ?? iif( cFB == "", LTrim( Str( n ) ), cFB ) + iif( n == 100, ".", ", " )   NEXT    RETURN 

The advantage of this approach is that it is trivial to add another factor:

AEval( {{3,"Fizz"},{5,"Buzz"},{9,"Jazz"}}, {|x| cFB += Iif((n % x[1])==0, x[2], "")})

## CLIPS

(deffacts count  (count-to 100)) (defrule print-numbers  (count-to ?max)  =>  (loop-for-count (?num ?max) do    (if      (= (mod ?num 3) 0)      then      (printout t "Fizz")    )    (if      (= (mod ?num 5) 0)      then      (printout t "Buzz")    )    (if      (and (> (mod ?num 3) 0) (> (mod ?num 5) 0))      then      (printout t ?num)    )    (priint depth, unsigned int i> struct NUM_DIGITS_CORE : NUM_DIGITS_COREntout t crlf)  ))

## Clojure

 (doseq [x (range 1 101)] (println x (str (when (zero? (mod x 3)) "fizz") (when (zero? (mod x 5)) "buzz")))) 
 (defn fizzbuzz [start finish]   (map (fn [n]	(cond		(zero? (mod n 15)) "FizzBuzz"		(zero? (mod n 3)) "Fizz"		(zero? (mod n 5)) "Buzz"		:else n))	(range start finish)))(fizzbuzz 1 100) 
(map (fn [x] (cond (zero? (mod x 15)) "FizzBuzz"                    (zero? (mod x 5)) "Buzz"                   (zero? (mod x 3)) "Fizz"		     :else x))     (range 1 101))
(map #(let [s (str (if (zero? (mod % 3)) "Fizz") (if (zero? (mod % 5)) "Buzz"))] (if (empty? s) % s)) (range 1 101))
(def fizzbuzz (map   #(cond (zero? (mod % 15)) "FizzBuzz"         (zero? (mod % 5)) "Buzz"         (zero? (mod % 3)) "Fizz"               :else %)  (iterate inc 1)))
(defn fizz-buzz   ([] (fizz-buzz (range 1 101)))  ([lst]     (letfn [(fizz? [n] (zero? (mod n 3)))	     (buzz? [n] (zero? (mod n 5)))]       (let [f     "Fizz" 	     b     "Buzz" 	     items (map (fn [n]			  (cond (and (fizz? n) (buzz? n)) (str f b)				(fizz? n) f				(buzz? n) b				:else n))			lst)] items))))
(map (fn [n]        (if-let [fb (seq (concat (when (zero? (mod n 3)) "Fizz")                                (when (zero? (mod n 5)) "Buzz")))]           (apply str fb)           n))     (range 1 101))
(take 100 (map #(let [s (str %2 %3) ] (if (seq s) s (inc %)) )            (range)            (cycle [ "" "" "Fizz" ])            (cycle [ "" "" "" "" "Buzz" ])))
(map #(nth (conj (cycle [% % "Fizz" % "Buzz" "Fizz" % % "Fizz" "Buzz" % "Fizz" % % "FizzBuzz"]) %) %) (range 1 101))
(let [n nil fizz (cycle [n n "fizz"]) buzz (cycle [n n n n "buzz"]) nums (iterate inc 1)]  (take 20 (map #(if (or %1 %2) (str %1 %2) %3) fizz buzz nums)))
(take 100      (map #(if (pos? (compare %1 %2)) %1 %2)           (map str (drop 1 (range)))           (map str (cycle ["" "" "Fizz"]) (cycle ["" "" "" "" "Buzz"])))) 
 ;;Using clojure maps(defn fizzbuzz  [n]  (let [rule {3 "Fizz"              5 "Buzz"}        divs (->> rule                  (map first)                  sort                  (filter (comp (partial = 0)                                (partial rem n))))]    (if (empty? divs)      (str n)      (->> divs           (map rule)           (apply str))))) (defn allfizzbuzz  [max]  (map fizzbuzz (range 1 (inc max)))) 
 (take 100   (map #(str %1 %2 (if-not (or %1 %2) %3))        (cycle [nil nil "Fizz"])        (cycle [nil nil nil nil "Buzz"])        (rest (range))   )) 
 (take 100  (    (fn [& fbspec]      (let [             fbseq #(->> (repeat nil) (cons %2) (take %1) reverse cycle)             strfn #(apply str (if (every? nil? (rest %&)) (first %&)) (rest %&))          ]        (->>          fbspec          (partition 2)          (map #(apply fbseq %))          (apply map strfn (rest (range)))          ) ;;endthread      ) ;;endlet    ) ;;endfn    3 "Fizz" 5 "Buzz" 7 "Bazz"  ) ;;endfn apply) ;;endtake 
 (take 100      (map-indexed        #(case %2 14 "FizzBuzz" (2 5 8 11) "Fizz" (4 9) "Buzz" (inc %1))        (cycle (range 15))        )) 
 (take 100       (->>          (map str (cycle [nil nil "Fizz"]) (cycle [nil nil nil nil "Buzz"]))          (map-indexed #(if (empty? %2) (inc %1) %2))       )) 
 (take 100    (map-indexed      #(if (number? %2) (+ %1 %2) %2)      (cycle [1 1 "Fizz" 1 "Buzz" "Fizz" 1 1 "Fizz" "Buzz" 1 "Fizz" 1 1 "FizzBuzz"])      )) 

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

## D

import std.stdio, std.algorithm, std.conv; /// With if-else.void fizzBuzz(in uint n) {    foreach (immutable i; 1 .. n + 1)        if (!(i % 15))            "FizzBuzz".writeln;        else if (!(i % 3))            "Fizz".writeln;        else if (!(i % 5))            "Buzz".writeln;        else            i.writeln;} /// With switch case.void fizzBuzzSwitch(in uint n) {    foreach (immutable i; 1 .. n + 1)        switch (i % 15) {            case 0:                "FizzBuzz".writeln;                break;            case 3, 6, 9, 12:                "Fizz".writeln;                break;            case 5, 10:                "Buzz".writeln;                break;            default:                i.writeln;        }} void fizzBuzzSwitch2(in uint n) {    foreach (immutable i; 1 .. n + 1)        (i % 15).predSwitch(        0,       "FizzBuzz",        3,       "Fizz",        5,       "Buzz",        6,       "Fizz",        9,       "Fizz",        10,      "Buzz",        12,      "Fizz",        /*else*/ i.text).writeln;} void main() {    100.fizzBuzz;    writeln;    100.fizzBuzzSwitch;    writeln;    100.fizzBuzzSwitch2;}

Alternate version calculating values at compile time:

import std; void main(){    auto fizzbuzz(in uint i)    {        string r;        if (i % 3 == 0) r ~= "fizz";        if (i % 5 == 0) r ~= "buzz";        if (r.length == 0) r ~= i.to!string;        return r;    }     enum r = 1.iota(101).map!fizzbuzz;     r.each!writeln;}

## Dart

 main() {  for (int i = 1; i <= 100; i++) {    List<String> out = [];    if (i % 3 == 0)      out.add("Fizz");    if (i % 5 == 0)      out.add("Buzz");    print(out.length > 0 ? out.join("") : i);  }} 

## dc

Translation of: bc
[[Fizz]P 1 sw]sF[[Buzz]P 1 sw]sB[li p sz]sN[[]P]sW[ 0 sw         [w = 0]sz li 3 % 0 =F  [Fizz if 0 == i % 3]sz li 5 % 0 =B  [Buzz if 0 == i % 5]sz lw 0 =N      [print Number if 0 == w]sz lw 1 =W      [print neWline if 1 == w]sz li 1 + si    [i += 1]sz li 100 !<L   [continue Loop if 100 >= i]sz ]sL1 si          [i = 1]sz0 0 =L        [enter Loop]sz

The bc translation written in dc style.

 # dc is stack based, so we use the stack instead of a variable for our # current number. 1                       # Number = 1[[Fizz]n 1 sw]sF        # Prints "Fizz" prevents Number from printing[[Buzz]n 1 sw]sB        # Prints "Buzz" prevents Number from printing[dn]sN                  # Prints Number[        dd              # Put two extra copies of Number on stack        0 sw            # w = 0        3% 0=F          # Fizz if 0 == Number % 3 (destroys 1st copy)        5% 0=B          # Buzz if 0 == Number % 5 (destroys 2nd copy)        lw 0=N          # Print Number if 0 == w        []n                      # Print new line        1+d             # Number += 1 and put extra copy on stack        100!<L          # Continue Loop if 100 >= Number (destroys copy)]dsLx                   # Enter Loop

## 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 "NSLog.incl" long fizz, buzz, i for i = 1 to 100  fizz = (i mod 3 )  buzz = (i mod 5 )  if fizz + buzz == 0 then NSLog(@"FizzBuzz") : continue  if fizz == 0 then NSLog(@"Fizz") : continue  if buzz == 0 then NSLog(@"Buzz") : continue  NSLog(@"%ld",i)next i HandleEvents

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


## Fōrmulæ

Fōrmulæ programs are not textual, visualization/edition of programs is done showing/manipulating structures but not text. Moreover, there can be multiple visual representations of the same program. Even though it is possible to have textual representation —i.e. XML, JSON— they are intended for storage and transfer purposes more than visualization and edition.

Programs in Fōrmulæ are created/edited online in its website, However they run on execution servers. By default remote servers are used, but they are limited in memory and processing power, since they are intended for demonstration and casual use. A local server can be downloaded and installed, it has no limitations (it runs in your own computer). Because of that, example programs can be fully visualized and edited, but some of them will not run if they require a moderate or heavy computation/memory resources, and no local server is being used.

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

## Gleam

import gleam/intimport gleam/ioimport gleam/iterator pub fn main() {  iterator.range(1, 101)  |> iterator.map(to_fizzbuzz)  |> iterator.map(io.println)  |> iterator.run} fn to_fizzbuzz(n: Int) -> String {  case n % 3, n % 5 {    0, 0 -> "FizzBuzz"    0, _ -> "Fizz"    _, 0 -> "Buzz"    _, _ -> int.to_string(n)  }}

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

## Golfscript

100,{)6,{.(&},{1$1$%{;}{4*35+6875*25base{90\-}%}if}%\or}%n*

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

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:

import Data.Monoid fizzbuzz = max       <$> show <*> "fizz" when divisibleBy 3 <> "buzz" when divisibleBy 5 <> "quxx" when divisibleBy 7 where when m p x = if p x then m else mempty divisibleBy n x = x mod n == 0 main = mapM_ (putStrLn . fizzbuzz) [1..100] And pattern matching approach: fizzbuzz n = case (rem n 3, rem n 5) of (0, 0) -> "FizzBuzz" (0, _) -> "Fizz" (_, 0) -> "Buzz" (_, _) -> show n main = mapM_ (putStrLn . fizzbuzz) [1..100] Generalised solution: wordthing :: [(Int, String)] -> Int -> Stringwordthing lst n = if matches == [] then show n else concat$ map snd matches  where matches = filter (\x -> n mod (fst x) == 0) lst fizzbuzz :: Int -> Stringfizzbuzz = wordthing [(3, "Fizz"), (5, "Buzz")] main = do  mapM_ (putStrLn . fizzbuzz) [1..100]

## hexiscript

for let i 1; i <= 100; i++  if   i % 3 = 0 && i % 5 = 0; println "FizzBuzz"  elif i % 3 = 0; println "Fizz"  elif i % 5 = 0; println "Buzz"  else println i; endifendfor

## HicEst

DO i = 1, 100  IF(     MOD(i, 15) == 0 ) THEN    WRITE() "FizzBuzz"  ELSEIF( MOD(i, 5) == 0 ) THEN    WRITE() "Buzz"  ELSEIF( MOD(i, 3) == 0 ) THEN    WRITE() "Fizz"  ELSE    WRITE() i  ENDIFENDDO

Alternatively:

CHARACTER string*8 DO i = 1, 100  string = " "  IF( MOD(i, 3) == 0 ) string = "Fizz"  IF( MOD(i, 5) == 0 ) string = TRIM(string) // "Buzz"  IF( string == " ") WRITE(Text=string) i  WRITE() stringENDDO

## HolyC

U8 i;for (i = 1; i <= 100; i++) {  if (!(i % 15))    Print("FizzBuzz");  else if (!(i % 3))    Print("Fizz");  else if (!(i % 5))    Print("Buzz");  else    Print("%d", i);  Print("\n");}

## Hoon

:-  %say|=  [^ ~ ~]  :-  %noun  %+  turn   (gulf [1 101])  |=  [email protected]    =+  q=[=(0 (mod a 3)) =(0 (mod a 5))]    ?+  q  <a>      [& &]  "FizzBuzz"      [& |]  "Fizz"      [| &]  "Buzz"    ==

## Huginn

import Algorithms as algo; main( argv_ ) {	if ( size( argv_ ) < 2 ) {		throw Exception( "usage: fizzbuzz {NUM}" );	}	top = integer( argv_[1] );	for ( i : algo.range( 1, top + 1 ) ) {		by3 = ( i % 3 ) == 0;		by5 = ( i % 5 ) == 0;		if ( by3 ) {			print( "fizz" );		}		if ( by5 ) {			print( "buzz" );		}		if ( ! ( by3 || by5 ) ) {			print( i );		}		print( "\n" );	}	return ( 0 );}

## Hy

(for [i (range 1 101)] (print (cond  [(not (% i 15)) "FizzBuzz"]  [(not (% i  5)) "Buzz"]  [(not (% i  3)) "Fizz"]  [True           i])))

## i

software {	for each 1 to 100				if i % 15 = 0			print("FizzBuzz")		else if i % 3 = 0			print("Fizz")		else if i % 5 = 0			print("Buzz")		else			print(i)		end	end}

## Icon and Unicon

# straight-forward modulo testerprocedure main()    every i := 1 to 100 do        if i % 15 = 0 then            write("FizzBuzz")        else if i % 5 = 0 then            write("Buzz")        else if i % 3 = 0 then            write("Fizz")        else            write(i)end
# idiomatic modulo tester, 1st alternativeprocedure main()    every i := 1 to 100 do        write((i % 15 = 0 & "FizzBuzz") | (i % 5 = 0 & "Buzz") | (i % 3 = 0 & "Fizz") | i)end
# idiomatic modulo tester, 2nd alternativeprocedure main()    every i := 1 to 100 do        write(case 0 of {                 i % 15 : "FizzBuzz"                 i % 5  : "Buzz"                 i % 3  : "Fizz"                 default: i        })end
# straight-forward buffer builderprocedure main()    every i := 1 to 100 do {        s := ""        if i % 3 = 0 then            s ||:= "Fizz"        if i % 5 = 0 then            s ||:= "Buzz"        if s == "" then            s := i        write(s)    }end
# idiomatic buffer builder, 1st alternativeprocedure main()    every i := 1 to 100 do        write("" ~== (if i % 3 = 0 then "Fizz" else "") || (if i % 5 == 0 then "Buzz" else "") | i)end
# idiomatic buffer builder, 2nd alternativeprocedure main()    every i := 1 to 100 do {        s   := if i%3 = 0 then "Fizz" else ""        s ||:= if i%5 = 0 then "Buzz"        write(("" ~= s) | i)    }end

## Joy

The following program first defines a function "one", which handles the Fizz / Buzz logic, and then loops from 1 to 100 mapping the function onto each number, and printing ("put") the output.

DEFINE one == [[[dup 15 rem 0 =] "FizzBuzz"] [[dup 3 rem 0 =] "Fizz"] [[dup 5 rem 0 =] "Buzz"] [dup]] cond.1 [100 <=] [dup one put succ] while.

## jq

range(1;101)  | if   . % 15 == 0 then "FizzBuzz"    elif . % 5  == 0 then "Buzz"    elif . % 3  == 0 then "Fizz"    else .    end

Another solution:

range(100) + 1 | [(	(select(. % 3 == 0) | "Fizz"),	(select(. % 5 == 0) | "Buzz")) // tostring] | join("")

## Julia

Works with: Julia version 0.6

One basic solution:

for i in 1:100    if i % 15 == 0        println("FizzBuzz")    elseif i % 3 == 0        println("Fizz")    elseif i % 5 == 0        println("Buzz")    else        println(i)    endend

Another possible solution:

collect(i % 15 == 0 ? "FizzBuzz" : i % 5 == 0 ? "Buzz" : i % 3 == 0 ? "Fizz" : i for i in 1:100) |> println

A 3rd possible solution:

fb(i::Integer) = "Fizz" ^ (i % 3 == 0) * "Buzz" ^ (i % 5 == 0) * dec(i) ^ (i % 3 != 0 && i % 5 != 0)for i in 1:100 println(fb(i)) end

A 4th one:

println.(map(fb, 1:100))

A fifth (DRY, Don't Repeat Yourself) possible solution:

for i in 1:100    msg = "Fizz" ^ (i % 3 == 0) * "Buzz" ^ (i % 5 == 0)    println(isempty(msg) ? i : msg)end

## K

### Solution 0

0:\:{:[0=#a:{,/$(:[0=x!3;"Fizz"];:[0=x!5;"Buzz"])}@x;$x;a]}'1_!101

For kona:
Output:

## make

Works with: BSD make
Library: jot

## Mercury

:- module fizzbuzz.:- interface.:- import_module io.:- pred main(io::di, io::uo) is det.:- implementation.:- import_module int, string, bool. :- func fizz(int) = bool.fizz(N) = ( if N mod 3 = 0 then yes else no ). :- func buzz(int) = bool.buzz(N) = ( if N mod 5 = 0 then yes else no ). %                N    3?    5?:- func fizzbuzz(int, bool, bool) = string.fizzbuzz(_, yes, yes) = "FizzBuzz".fizzbuzz(_, yes, no)  = "Fizz".fizzbuzz(_, no,  yes) = "Buzz".fizzbuzz(N, no,  no)  = from_int(N). main(!IO) :- main(1, 100, !IO). :- pred main(int::in, int::in, io::di, io::uo) is det.main(N, To, !IO) :-    io.write_string(fizzbuzz(N, fizz(N), buzz(N)), !IO),    io.nl(!IO),    ( if N < To then        main(N + 1, To, !IO)    else        true    ).

## Metafont

for i := 1 upto 100:message if i mod 15 = 0: "FizzBuzz" &elseif i mod 3 = 0: "Fizz" &elseif i mod 5 = 0: "Buzz" &else: decimal i & fi "";endforend

## Microsoft Small Basic

Translation of: GW-BASIC
 For n = 1 To 100  op = ""  If Math.Remainder(n, 3) = 0 Then    op = "Fizz"  EndIf    IF Math.Remainder(n, 5) = 0 Then    op = text.Append(op, "Buzz")  EndIf  If op = "" Then     TextWindow.WriteLine(n)  Else     TextWindow.WriteLine(op)  EndIf  EndFor

## min

Works with: min version 0.19.3
0 (  succ false :hit  (3 mod 0 ==) ("Fizz" print! true @hit) when  (5 mod 0 ==) ("Buzz" print! true @hit) when  (hit) (print) unless newline) 100 times

## MiniScript

for i in range(1,100)    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    end ifend for

## MIPS Assembly

 ################################## Fizz Buzz                     ## MIPS Assembly targetings MARS ## By Keith Stellyes             ## August 24, 2016               ################################## # $a0 left alone for printing#$a1 stores our counter# $a2 is 1 if not evenly divisible .data fizz: .asciiz "Fizz\n" buzz: .asciiz "Buzz\n" fizzbuzz: .asciiz "FizzBuzz\n" newline: .asciiz "\n" .textloop: beq$a1,100,exit	add $a1,$a1,1 	#test for counter mod 15 ("FIZZBUZZ")	div $a2,$a1,15	mfhi $a2 bnez$a2,loop_not_fb #jump past the fizzbuzz print logic if NOT MOD 15 #### PRINT FIZZBUZZ: ####	li $v0,4 #set syscall arg to PRINT_STRING la$a0,fizzbuzz #set the PRINT_STRING arg to fizzbuzz	syscall #call PRINT_STRING	j loop #return to start#### END PRINT FIZZBUZZ #### loop_not_fb:		div $a2,$a1,3 #divide $a1 (our counter) by 3 and store remainder in HI mfhi$a2 #retrieve remainder (result of MOD)	bnez $a2, loop_not_f #jump past the fizz print logic if NOT MOD 3 #### PRINT FIZZ #### li$v0,4 	la $a0,fizz syscall j loop#### END PRINT FIZZ #### loop_not_f: div$a2,$a1,5 mfhi$a2	bnez $a2,loop_not_b #### PRINT BUZZ #### li$v0,4 	la $a0,buzz syscall j loop#### END PRINT BUZZ #### loop_not_b: #### PRINT THE INTEGER #### li$v0,1 #set syscall arg to PRINT_INTEGER	move $a0,$a1 #set PRINT_INTEGER arg to contents of $a1 syscall #call PRINT_INTEGER ### PRINT THE NEWLINE CHAR ### li$v0,4 #set syscall arg to PRINT_STRING	la $a0,newline syscall j loop #return to beginning exit: li$v0,10	syscall

## Mirah

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

A little more straight forward:

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

## ML

### Standard ML

First using two helper functions, one for deciding what to output and another for performing recursion with an auxiliary argument j.

local  fun fbstr i =      case (i mod 3 = 0, i mod 5 = 0) of          (true , true ) => "FizzBuzz"        | (true , false) => "Fizz"        | (false, true ) => "Buzz"        | (false, false) => Int.toString i   fun fizzbuzz' (n, j) =      if n = j then () else (print (fbstr j ^ "\n"); fizzbuzz' (n, j+1))in  fun fizzbuzz n = fizzbuzz' (n, 1)  val _ = fizzbuzz 100end

Second using the standard-library combinator List.tabulate and a helper function, fb, that calculates and prints the output.

local  fun fb i = let val fizz = i mod 3 = 0 andalso (print "Fizz"; true)                 val buzz = i mod 5 = 0 andalso (print "Buzz"; true)             in fizz orelse buzz orelse (print (Int.toString i); true) endin  fun fizzbuzz n = (List.tabulate (n, fn i => (fb (i+1); print "\n")); ())  val _ = fizzbuzz 100end

### mLite

local	fun fizzbuzz' 			(x mod 15 = 0) = "FizzBuzz"		|	(x mod  5 = 0) = "Buzz"		|	(x mod  3 = 0) = "Fizz"		|	x = ntos xin			fun fizzbuzz			([], s) = rev s		|	(x :: xs, s) = fizzbuzz (xs, fizzbuzz' x :: s)		|	(x :: xs)    = fizzbuzz (x :: xs, [])end; println  fizzbuzz  iota 100;

## MMIX

t   IS $255Ja IS$127        LOC Data_Segmentdata   GREG   @ fizz   IS @-Data_Segment       BYTE "Fizz",0,0,0,0 buzz   IS @-Data_Segment       BYTE "Buzz",0,0,0,0 nl     IS @-Data_Segment       BYTE #a,0,0,0,0,0,0,0 buffer IS @-Data_Segment          LOC #1000       GREG @% "usual" print integer subroutineprintnum LOC @       OR   $1,$0,0       SETL $2,buffer+64 ADDU$2,$2,data XOR$3,$3,$3       STBU $3,$2,1loop   DIV  $1,$1,10       GET  $3,rR ADDU$3,$3,'0' STBU$3,$2,0 SUBU$2,$2,1 PBNZ$1,loop       ADDU t,$2,1 TRAP 0,Fputs,StdOut GO Ja,Ja,0 Main SETL$0,1           % i = 11H     SETL $2,0 % fizz not taken CMP$1,$0,100 % i <= 100 BP$1,4F          % if no, go to end       DIV  $1,$0,3       GET  $1,rR %$1 = mod(i,3)       CSZ  $2,$1,1        % $2 = Fizz taken? BNZ$1,2F          % $1 != 0? yes, then skip ADDU t,data,fizz TRAP 0,Fputs,StdOut % print "Fizz"2H DIV$1,$0,5 GET$1,rR          % $1 = mod(i,5) BNZ$1,3F          % $1 != 0? yes, then skip ADDU t,data,buzz TRAP 0,Fputs,StdOut % print "Buzz" JMP 5F % skip print i3H BP$2,5F          % skip if Fizz was taken       GO   Ja,printnum    % print i5H     ADDU t,data,nl       TRAP 0,Fputs,StdOut % print newline       ADDU $0,$0,1       JMP  1B             % repeat for next i4H     XOR  t,t,t       TRAP 0,Halt,0       % exit(0)

## Modula-2

MODULE Fizzbuzz;FROM FormatString IMPORT FormatString;FROM Terminal IMPORT WriteString,WriteLn,ReadChar; TYPE CB = PROCEDURE(INTEGER); PROCEDURE Fizz(n : INTEGER);BEGIN    IF n MOD 3 = 0 THEN        WriteString("Fizz");        Buzz(n,Newline)    ELSE        Buzz(n,WriteInt)    ENDEND Fizz; PROCEDURE Buzz(n : INTEGER; f : CB);BEGIN    IF n MOD 5 = 0 THEN        WriteString("Buzz");        WriteLn    ELSE        f(n)    ENDEND Buzz; PROCEDURE WriteInt(n : INTEGER);VAR buf : ARRAY[0..9] OF CHAR;BEGIN    FormatString("%i\n", buf, n);    WriteString(buf)END WriteInt; PROCEDURE Newline(n : INTEGER);BEGIN    WriteLnEND Newline; VAR i : INTEGER;BEGIN    FOR i:=1 TO 30 DO        Fizz(i)    END;     ReadCharEND Fizzbuzz.

## Modula-3

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

def fizzBuzz(top):    var t := 1    while (t < top):        if ((t % 3 == 0) || (t % 5 == 0)):            if (t % 15 == 0):                traceln($t FizzBuzz) else if (t % 3 == 0): traceln($t  Fizz)            else:                traceln($t Buzz) t += 1 fizzBuzz(100)  ## 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 ""} ## MUMPS 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

## NATURAL

 DEFINE DATA                               LOCAL                                     1 #I       (I4)                           1 #MODULO  (I4)                           1 #DIVISOR (I4)                           1 #OUT     (A10)                          END-DEFINE                                *                                         FOR #I := 1 TO 100                          #DIVISOR := 15                            #OUT := 'FizzBuzz'                        PERFORM MODULO                          *                                           #DIVISOR := 5                             #OUT := 'Buzz'                            PERFORM MODULO                          *                                           #DIVISOR := 3                             #OUT := 'Fizz'                            PERFORM MODULO                          *                                           WRITE #I                                END-FOR                                   *                                         DEFINE SUBROUTINE MODULO                  #MODULO := #I - (#I / #DIVISOR) * #DIVISORIF #MODULO = 0                              WRITE NOTITLE #OUT                        ESCAPE TOP                              END-IF                                    END-SUBROUTINE                            *                                         END

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

### Using macro

Computes everything at compile time.

## 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 <Foundation/Foundation.h> int main(int argc, char* argv[]) {	for (NSInteger i=1; I <= 101; i++) {		if (i % 15 == 0) {		    NSLog(@"FizzBuzz\n");		} else if (i % 3 == 0) {		    NSLog(@"Fizz\n");		} else if (i % 5 == 0) {		    NSLog(@"Buzz\n");		} else {		    NSLog(@"%li\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 ] .       ] ;

## Ol

 (for-each (lambda (x)      (print (cond         ((and (zero? (mod x 3)) (zero? (mod x 5)))            "FizzBuzz")         ((zero? (mod x 3))            "Fizz")         ((zero? (mod x 5))            "Buzz")         (else            x))))   (iota 100))

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

## Picat

First some "standalone" predicates.

### Using a map

fizzbuzz_map =>    println(fizzbuzz_map),    FB = [I : I in 1..100],    Map = [(3="Fizz"),(5="Buzz"),(15="FizzBuzz")],    foreach(I in FB, K=V in Map)        if I mod K == 0 then          FB[I] := V       end    end,    println(FB).

### Using a template for the pattern

fizzbuzz_template1 =>   println(fizzbuzz_template1),   N = 100,   F = [_,_,fizz,_,buzz,fizz,_,_,fizz,buzz,_,fizz,_,_,fizzbuzz],   FF = [F : _I in 1..1+N div F.length].flatten(),   foreach(I in 1..N)      (var(FF[I]) -> print(I) ; print(FF[I])),      print(" ")   end,   nl.

### Another version with templates

fizzbuzz_template2 =>   println(fizzbuzz_template2),   N = 100,   F = new_list(N),   FV = [3,5,15],   FN = ["Fizz","Buzz","FizzBuzz"],   foreach(I in 1..N, {Val,Name} in zip(FV,FN))       if I mod Val == 0 then F[I] := Name end   end,   foreach(I in 1..N)      printf("%w ", cond(var(F[I]),I, F[I]))   end,   nl.

Below are some versions for identifying the FizzBuzziness of a number. To be used with the following general wrapper:

fizzbuzz(Goal) =>     println(Goal),    foreach(I in 1..100)       printf("%w ", apply(Goal,I))    end,    nl.

### Plain imperative approach: if/else

fb1(I) = V =>   V = I.to_string(),   if     I mod 15 == 0 then V := "FizzBuzz"   elseif I mod  3 == 0 then V := "Fizz"    elseif I mod  5 == 0 then V := "Buzz"    end.

### Pattern matching + conditions in head

fb2(I) = "FizzBuzz", I mod 15 == 0 => true.fb2(I) = "Fizz",     I mod  3 == 0 => true.fb2(I) = "Buzz",     I mod  5 == 0 => true.fb2(I) = I.to_string()             => true.

### Another pattern matching approach

fb3(I) = fb3b(I, I mod 3, I mod 5).fb3b(_I,0,0) = "FizzBuzz".fb3b(_I,_,0) = "Buzz".fb3b(_I,0,_) = "Fizz".fb3b(I,_,_)  = I.

### Using cond/3 and string concatenation

fb4(I) = cond(I mod 3 == 0, "Fizz", "") ++          cond(I mod 5 == 0, "Buzz", "")  ++         cond(not ((I mod 3 == 0; I mod 5==0)), I.to_string(), "").

### Recursive function (conditions in head)

fizzbuzz_rec =>  print(fizzbuzz_rec),  fb5(100,[],L),  println(L). fb5(N,L1,L), N = 0 ?=>  L = L1.reverse().fb5(N,L1,L),N mod 15 == 0 ?=>  fb5(N-1,L1 ++ ["FizzBuzz"], L).fb5(N,L1,L), N mod 5 == 0 ?=>  fb5(N-1,L1 ++ ["Buzz"], L).fb5(N,L1,L), N mod 3 == 0 ?=>  fb5(N-1,L1 ++ ["Fizz"], L).fb5(N,L1,L), N mod 3 > 0, N mod 5 > 0 =>  fb5(N-1,L1 ++ [N.to_string()], L).

### Golfing style

fizzbuzz_golf =>   println(fizzbuzz_golf),   [cond(P=="",I,P):I in 1..100,(I mod 3==0->P="Fizz";P=""),(I mod 5==0->P:=P++"Buzz";true)].println().

### Planner version

Picat has support for "classic" planning problems. The planner module must be imported.

import planner.fizzbuzz_planner =>   println(fizzbuzz_planner),   plan(100,Plan),   println(Plan.reverse()),   nl. final(Goal) => Goal == 0. action(H,To,Move,Cost) ?=>   H mod 15 == 0,  Move = "FizzBuzz",  To = H-1,  Cost = 1. action(H,To,Move,Cost) ?=>   H mod 5 == 0,  Move = "Buzz",  To = H-1,  Cost = 1. action(H,To,Move,Cost) ?=>   H mod 3 == 0,  Move = "Fizz",  To = H-1,  Cost = 1. action(H,To,Move,Cost) =>   H mod 3 > 0,  H mod 5 > 0,  Move = H.to_string(),  To = H-1,  Cost = 1.

Here we test everything.

go =>  fizzbuzz_map,  fizzbuzz_template1,  fizzbuzz_template2,  fizzbuzz_planner,  fizzbuzz_rec,  fizzbuzz_golf,   FBs = [fb1,fb2,fb3,fb4],  foreach(FB in FBs)    call(fizzbuzz,FB)  end,  nl.

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

100H: /* DECLARE OUTPUT IN TERMS OF CP/M -    PL/M DOES NOT COME WITH ANY STANDARD LIBRARY */BDOS: PROCEDURE(FUNC, ARG);    DECLARE FUNC BYTE, ARG ADDRESS;    GO TO 5;END BDOS; PUT$STRING: PROCEDURE(STR); DECLARE STR ADDRESS; CALL BDOS(9, STR); CALL BDOS(9, .(13,10,'$'));END PUT$STRING; /* PRINT A NUMBER */PUT$NUMBER: PROCEDURE(N);    DECLARE S (5) BYTE INITIAL ('...$'); DECLARE P ADDRESS; DECLARE (N, D, C BASED P) BYTE; P = .S(3);DIGIT: P = P-1; C = (N MOD 10) + '0'; N = N/10; IF N > 0 THEN GO TO DIGIT; CALL PUT$STRING(P);END PUT$NUMBER; /* FIZZBUZZ */DECLARE N BYTE;DO N = 1 TO 100; IF N MOD 15 = 0 THEN CALL PUT$STRING(.'FIZZBUZZ$'); ELSE IF N MOD 5 = 0 THEN CALL PUT$STRING(.'BUZZ$'); ELSE IF N MOD 3 = 0 THEN CALL PUT$STRING(.'FIZZ$'); ELSE CALL PUT$NUMBER(N);END; /* EXIT TO CP/M */CALL BDOS(0,0);EOF

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

## QB64

For n = 1 To 100    If n Mod 15 = 0 Then        Print "FizzBuzz"    ElseIf n Mod 5 = 0 Then        Print "Buzz"    ElseIf n Mod 3 = 0 Then        Print "Fizz"    Else        Print n    End IfNext

## Quackery

  [ times      [ i^ 1+        ' echo        over 3 mod 0 = if          [ say "Fizz"            drop ' drop ]        over 5 mod 0 = if          [ say "Buzz"            drop ' drop ]        do        sp ]    cr ]                  is fizzbuzz ( n --> )   say 'First 100 turns in the game of fizzbuzz:' cr cr  100 fizzbuzz cr

## 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 <- paste0(rep("", 100), c("", "", "Fizz"), c("", "", "", "", "Buzz"))cat(ifelse(x == "", 1:100, x), sep = "\n")

Or, for an abuse of the recycling rules that could be generalised:

x <- paste0(rep("", 100), rep(c("", "Fizz"), times = c(2, 1)), rep(c("", "Buzz"), times = c(4, 1)))cat(ifelse(x == "", 1:100, x), sep = "\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)))

Or, adapting from General FizzBuzz#Names solution:

namedNums <- c(Fizz = 3, Buzz = 5)for(i in 1:100){  isFactor <- i %% namedNums == 0  print(if(any(isFactor)) paste0(names(namedNums)[isFactor], collapse = "") else i)}

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

## Red

Red ["FizzBuzz"] repeat i 100 [    print case [        i % 15 = 0 ["FizzBuzz"]        i % 5 = 0 ["Buzz"]        i % 3 = 0 ["Fizz"]        true [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

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!

Using Ruby 3's Pattern Matching:

 1.upto(100) do |n|  puts case [(n % 3).zero?, (n % 5).zero?]       in true, false         "Fizz"       in false, true         "Buzz"       in true, true         "FizzBuzz"       else         n       endend

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

Basic example with a for loop and match:

fn main() {    for i in 1..=100 {        match (i % 3, i % 5) {            (0, 0) => println!("fizzbuzz"),            (0, _) => println!("fizz"),            (_, 0) => println!("buzz"),            (_, _) => println!("{}", i),        }    }}

Using an iterator and immutable data:

use std::borrow::Cow; fn main() {    (1..=100)        .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));}

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..=100).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());}

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

## 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 fizzBuzzTerm(n: Int): String =  if (n % 15 == 0) "FizzBuzz"  else if (n % 3 == 0) "Fizz"  else if (n % 5 == 0) "Buzz"  else n.toString def fizzBuzz(): Unit = LazyList.from(1).take(100).map(fizzBuzzTerm).foreach(println)

### Scala 3 (Dotty)

Written so as to introduce changes, with comments.

def fizzBuzzTerm(n: Int): String | Int = // union types  (n % 3, n % 5) match // optional semantic indentation; no braces    case (0, 0) => "FizzBuzz"    case (0, _) => "Fizz"    case (_, 0) => "Buzz"    case _      => n // no need for .toString, thanks to union type  end match // optional end keyword, with what it's endingend fizzBuzzTerm // end also usable for identifiers val fizzBuzz = // no namespace object is required; all top level  LazyList.from(1).map(fizzBuzzTerm) @main def run(): Unit = // @main for main method; can take custom args  fizzBuzz.take(100).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)

Approach with maps and filters, easier to change, less readable than the previous.

(define (fizzbuzz x)  (let ([words '((3 . "Fizz")                 (5 . "Buzz"))])    (define (fbm x)      (let ([w (map cdr (filter (lambda (wo) (= 0 (modulo x (car wo)))) words))])        (if (null? w) x (apply string-append w))))    (for-each (cut format #t "~a~%" <>) (map fbm (iota x 1 1))))) (fizzbuzz 15)

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

## Seed7

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

## SenseTalk

repeat 100	put "" into output	if the counter is a multiple of 3 then		put "Fizz" after output	end if	if the counter is a multiple of 5 then		put "Buzz" after output	end if	if output is empty then		put the counter into output	end if	put outputend repeat

## SequenceL

import <Utilities/Conversion.sl>;import <Utilities/Sequence.sl>; main(args(2)) := 	let		result[i] := 				"FizzBuzz" when i mod 3 = 0 and i mod 5 = 0			else				"Fizz" when i mod 3 = 0			else				"Buzz" when i mod 5 = 0			else				intToString(i)			foreach i within 1 ... 100;	in		delimit(result, '\n');

## Shale

#!/usr/local/bin/shale string library r vari vari 1 ={ i 100 <= } {  r "" =  i 3 % 0 == { r r "fizz" concat string::() = } ifthen  i 5 % 0 == { r r "buzz" concat string::() = } ifthen  r "" equals string::() { i } { r } if i "%3d: %p\n" printf  i++} while

## Shen

(define fizzbuzz  101 -> (nl)  N -> (let divisible-by? (/. A B (integer? (/ A B)))         (cases (divisible-by? N 15) (do (output "Fizzbuzz!~%")                                         (fizzbuzz (+ N 1)))                (divisible-by? N 3) (do (output "Fizz!~%")                                        (fizzbuzz (+ N 1)))                (divisible-by? N 5) (do (output "Buzz!~%")                                        (fizzbuzz (+ N 1)))                true (do (output (str N))                          (nl)                         (fizzbuzz (+ N 1)))))) (fizzbuzz 1)

(defprolog fizz  0 <-- (is _ (output "Fizz"));  N <-- (when (> N 0)) (is N1 (- N 3)) (fizz N1);) (defprolog buzz  0 <-- (is _ (output "Buzz"));  N <-- (when (> N 0)) (is N1 (- N 5)) (buzz N1);) (define none  [] -> true  [true | _] -> false  [_ | B] -> (none B)) (define fizzbuzz  N M -> (nl) where (> N M)  N M -> (do    (if (none [(prolog? (receive N) (fizz N)) (prolog? (receive N) (buzz N))])      (output (str N))      (output "!")    )    (nl)    (fizzbuzz (+ N 1) M)  )) (fizzbuzz 1 100)

## Sidef

Structured:

{ |i|    if (i %% 3) {        print "Fizz"        i %% 5 && print "Buzz"        print "\n"    }    elsif (i %% 5) { say "Buzz" }    else  { say i }} * 100

Declarative:

func fizzbuzz({ _ %% 15 }) { "FizzBuzz" }func fizzbuzz({ _ %%  5 }) {     "Buzz" }func fizzbuzz({ _ %%  3 }) {     "Fizz" }func fizzbuzz(        n  ) {          n } for n in (1..100) { say fizzbuzz(n) }

One-liner:

{|i|say "#{<Fizz>[i%3]}#{<Buzz>[i%5]}"||i}*100

## Simula

begin    integer i;    for i := 1 step 1 until 100 do    begin        boolean fizzed;        fizzed := 0 = mod(i, 3);        if fizzed then            outtext("Fizz");        if mod(i, 5) = 0 then            outtext("Buzz")        else if not fizzed then            outint(i, 3);        outimage    end;end

## SkookumScript

Answer by printing out one of the 4 alternatives:

 1.to 100  [  println(    if idx.mod(15) = 0 ["FizzBuzz"]      idx.mod(3) = 0 ["Fizz"]      idx.mod(5) = 0 ["Buzz"]      else [idx]