FizzBuzz

From Rosetta Code
Revision as of 10:48, 23 September 2011 by 147.172.223.18 (talk) (→‎{{header|C sharp}}: namespace not necessary)
Task
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 numbers from 1 to 100. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz". [1]

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

ActionScript

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

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

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

} </lang>


8086 Assembly

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

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

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

                   ;kept in Binary Coded Decimal, in

                   ;the DX register.

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

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

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

                   ;for screen printing.

xor bh,bh  ; BH is the counter for counting

                   ;multiples of three.

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

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

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

                   ;screen.

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

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

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

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

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

                   ;multiples of three, is cleared.

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

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

writebuzz:  ; (The above code falls here if

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

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

                   ;loop.

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

                   ;both strings are 4 bytes long.

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

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

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

                   ;subroutine.

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

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

Ada

<lang ada>with Ada.Text_IO; use Ada.Text_IO;

procedure Fizzbuzz is begin

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

end Fizzbuzz;</lang>

ALGOL 68

<lang algol68>main:(

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

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

APL

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

AppleScript

<lang AppleScript> property outputText: "" repeat with i from 1 to 100

 if i mod 15 = 0 then
   set outputText to outputText & "FizzBuzz"
 else if i mod 3 = 0 then
   set outputText to outputText & "Fizz"
 else if i mod 5 = 0 then
   set outputText to outputText & "Buzz"
 else
   set outputText to outputText & i
 end if
 set outputText to outputText & linefeed

end repeat outputText </lang>

Arbre

<lang Arbre> fizzbuzz():

 for x in [1..100]
   if x%5==0 and x%3==0
     return "FizzBuzz"
   else
     if x%3==0
       return "Fizz"
     else
       if x%5==0
         return "Buzz"
       else
          return x

main():

 fizzbuzz() -> io

</lang>

AutoHotkey

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

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

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

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

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

Return Esc:: ExitApp</lang>

AWK

<lang AWK>BEGIN {

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

}</lang> <lang AWK> echo {1..100} | awk ' BEGIN{RS=" "} $1 % 15 == 0 {print "FizzBuzz"} $1 % 5 == 0 {print "Buzz"} $1 % 3 == 0 {print "Fizz"} {print} ' </lang> <lang AWK> seq 100 | awk '$0=NR%15?NR%5?NR%3?$0:"Fizz":"Buzz":"FizzBuzz"' </lang>

BASIC

Works with: QuickBasic version 4.5

If/else ladder approach

<lang qbasic>FOR A = 1 TO 100

  IF A MOD 15 = 0 THEN
     PRINT "FizzBuzz"
  ELSE IF A MOD 3 = 0 THEN
     PRINT "Fizz"
  ELSE IF A MOD 5 = 0 THEN
     PRINT "Buzz"
  ELSE
     PRINT A
  END IF

NEXT A</lang>

Concatenation approach

<lang qbasic>FOR A = 1 TO 100

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

NEXT A</lang>

See also: RapidQ

Batch File

For /L version: <lang dos>@echo off for /L %%i in (1,1,100) do call :tester %%i goto :eof

tester

set /a test = %1 %% 15 if %test% NEQ 0 goto :NotFizzBuzz echo FizzBuzz goto :eof

NotFizzBuzz

set /a test = %1 %% 5 if %test% NEQ 0 goto :NotBuzz echo Buzz goto :eof

NotBuzz

set /a test = %1 %% 3 if %test% NEQ 0 goto :NotFizz echo Fizz goto :eof

NotFizz

echo %1 </lang>

Loop version:

<lang dos>@echo off set n=1

loop

call :tester %n% set /a n += 1 if %n% LSS 101 goto loop goto :eof

tester

set /a test = %1 %% 15 if %test% NEQ 0 goto :NotFizzBuzz echo FizzBuzz goto :eof

NotFizzBuzz

set /a test = %1 %% 5 if %test% NEQ 0 goto :NotBuzz echo Buzz goto :eof

NotBuzz

set /a test = %1 %% 3 if %test% NEQ 0 goto :NotFizz echo Fizz goto :eof

NotFizz

echo %1 </lang>

BBC BASIC

<lang bbcbasic> FOR number% = 1 TO 100

       CASE TRUE OF
         WHEN number% MOD 15 = 0: PRINT "FizzBuzz"
         WHEN number% MOD 3 = 0:  PRINT "Fizz"
         WHEN number% MOD 5 = 0:  PRINT "Buzz"
         OTHERWISE: PRINT ; number%
       ENDCASE
     NEXT number%</lang>

bc

This solution never uses else, because bc has no else keyword (but some implementations add else as an extension).

<lang bc>for (i = 1; i <= 100; i++) { w = 0 if (i % 3 == 0) { "Fizz"; w = 1; } if (i % 5 == 0) { "Buzz"; w = 1; } if (w == 0) i if (w == 1) " " } quit</lang>

Befunge

(befunge 93)

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

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

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

    >:5%!|                                                                     

v "buzz"0<>:. ^

        |!%5:           <                                                      

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

Brat

<lang brat>1.to 100 { n |

 true? n % 15 == 0
   { p "FizzBuzz" }
   { true? n % 3 == 0
     { p "Fizz" }
     { true? n % 5 == 0
       { p "Buzz" }
       { p n }
     }
   }
 }</lang>

Brainf***

<lang bf> FizzBuzz

Memory:

 Zero
 Zero
 Counter 1
 Counter 2
 Zero
 ASCIIDigit 3
 ASCIIDigit 2
 ASCIIDigit 1
 Zero
 Digit 3
 Digit 2    
 Digit 1    
 CopyPlace
 Mod 3
 Mod 5
 PrintNumber
 TmpFlag

Counters for the loop ++++++++++[>++++++++++[>+>+<<-]<-]

Number representation in ASCII >>>> ++++++++ ++++++++ ++++++++ ++++++++ ++++++++ ++++++++ [>+>+>+<<<-] <<<<

>> [

   Do hundret times:
   Decrement counter
   ->->
   Increment Number
   > >>+> 
       > >>+>
       <<<<
   <<<<
   Check for Overflow
   ++++++++++
   >>> >>>>
   >++++++++++<
   [-<<< <<<<->>>> >>> >-<]
   ++++++++++ 
   <<< <<<<
   Restore the digit
   [->>>> >>>-<<< <<<<]
   >>>> [-]+ >>>>[<<<< - >>>>[-]]<<<< <<<< 
   If there is an overflow
   >>>>[
       <<<<
       >>>----------> >>>----------<+<< <<+<<
       Check for Overflow
       ++++++++++
       >> >>>>
       >>++++++++++<<
       [-<< <<<<->>>> >> >>-<<]
       ++++++++++ 
       << <<<<
       Restore the digit
       [->>>> >>-<< <<<<]
       >>>> [-]+ >>>>[<<<< - >>>>[-]]<<<< <<<< 
       If there (again) is an overflow
       >>>>[
           <<<<
           >>---------->> >>----------<+< <<<+<
           >>>>
           [-]
       ]<<<<
       >>>>
       [-]
   ]<<<<
   >>>> >>>> 
   Set if to print the number
   >>>[-]+<<<
   Handle the Mod 3 counter
   [-]+++
   >>>>[-]+<<<<
   >+[-<->]+++<
   [->->>>[-]<<<<]
   >>>>[
       <[-]>
       [-]
       Print "Fizz"
       ++++++++ ++++++++ ++++++++ ++++++++
       ++++++++ ++++++++ ++++++++ ++++++++
       ++++++.
       ++++++++ ++++++++ ++++++++ ++++++++
       +++.
       
       ++++++++ ++++++++ +..
       [-]
       <<<--->>>
   ]<<<<
   Handle the Mod 5 counter
   [-]+++++
   >>>>[-]+<<<<
   >>+[-<<->>]+++++<<
   [->>->>[-]<<<<]
   >>>>[
       <[-]>
       [-]
       Print "Buzz"
       ++++++++ ++++++++ ++++++++ ++++++++
       ++++++++ ++++++++ ++++++++ ++++++++
       ++.
       ++++++++ ++++++++ ++++++++ ++++++++
       ++++++++ ++++++++ +++.
       
       +++++..
       [-]
       <<----->>
   ]<<<<
   Check if to print the number (Leading zeros)
   >>>[
       <<< <<<< <<<<
       >.>.>.<<<
       >>> >>>> >>>>
       [-]
   ]<<<
   <<<< <<<<
   Print New Line
   <<<<[-]++++ ++++ ++++ +.---.[-]>>

] << </lang>

C

<lang c>#include<stdio.h>

int main (void) {

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

}</lang>

obfuscated:

<lang c>

  1. include <stdio.h>
  2. define F(x,y) printf("%s",i%x?"":#y"zz")

int main(int i){for(--i;i++^100;puts(""))F(3,Fi)|F(5,Bu)||printf("%i",i);return 0;}</lang>

This actually works (the array init part, saves 6 bytes of static data, whee):<lang c>#include<stdio.h>

int main () { int i; char *s[] = { "%d\n", "Fizz\n", s[3] + 4, "FizzBuzz\n" }; for (i = 1; i <= 100; i++) printf(s[!(i % 3) + 2 * !(i % 5)], i);

return 0; }</lang>

C++

<lang cpp>#include <iostream>

using namespace std; int main () {

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

}</lang>

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

int main() {

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

}</lang>

Another alternate version using functions and no modulo 15: <lang cpp>

  1. include <iostream>

bool special(int i, int factor, char const* word) {

 if (i % factor == 0)
 {
   std::cout << word;
   return true;
 }
 else
  return false;

}

int main() {

 for (int i = 0; i <= 100; ++i)
 {
   if (!(special(i, 3, "Fizz")
         | special(i, 5, "Buzz"))) // note: binary or, not logical or! (No short circuit)
     std::cout << i;
   std::cout << std::endl;
 }

} </lang>

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

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

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

};

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

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

};

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

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

};

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

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

};

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

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

};

template <int n> struct fb_run {

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

};

int main() {

 fb_run<100> fb;

}</lang>

Hardcore templates (compile with -ftemplate-depth-9000 -std=c++0x): <lang cpp>

  1. include <iostream>
  2. include <string>
  3. include <cstdlib>
  4. include <boost/mpl/string.hpp>
  5. include <boost/mpl/fold.hpp>
  6. include <boost/mpl/size_t.hpp>

using namespace std; using namespace boost;

/////////////////////////////////////////////////////////////////////////////// // exponentiation calculations template <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 calculations template <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 0000000017 template <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 character template <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 offsets template <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 on template <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 on template <unsigned int i, int offset>

   struct OFFSET_CHAR : OFFSET_CHAR_CORE<i, offset, NUM_DIGITS::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::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; } </lang> 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).

C#

<lang csharp>using System;

class Program {

   static void Main(string[] args)
   {
       for (int i = 1; i <= 100; i++)
       {
           string output = "";
           if (i % 3 == 0) output += "Fizz";
           if (i % 5 == 0) output += "Buzz";
           if (String.IsNullOrEmpty(output)) 
               output = i.ToString();
           Console.WriteLine(output);
       }
   }

}</lang>

Chef

This was clearly a challenge in a language without a modulus operator, a proper if statement except for checking if a variable is not exactly 0, and no way to define text except 1 character at a time on a stack.

<lang chef>Irish Soda Bread with Club Soda.

This is FizzBuzz

Ingredients. 1 l buttermilk

Method. Take buttermilk from refrigerator. Shake the buttermilk.

Put buttermilk into the 6th mixing bowl.
Serve with club soda.
Pour contents of the 1st mixing bowl into the 1st baking dish.
Clean the 1st mixing bowl.

Watch the buttermilk until shaked.

Serves 1.

Club Soda.

Gets whether to print fizz buzz fizzbuzz or number.

Ingredients. 70 g flour 105 g salt 122 ml milk 66 g sugar 117 ml vegetable oil 3 cups fizzle 5 cups seltzer 1 cup bmilk 1 cup ice 1 cup baking soda 1 g oregano 32 ml vinegar 1 g thyme 1 g sage

Method. Put milk into the 1st mixing bowl. Put salt into the 1st mixing bowl. Put flour into the 1st mixing bowl. Put vinegar into the 1st mixing bowl. Put milk into the 1st mixing bowl. Stir the 1st mixing bowl for 5 minutes. Liquify contents of the 1st mixing bowl. Put fizzle into the 3rd mixing bowl. Combine seltzer into the 3rd mixing bowl. Fold bmilk into the 6th mixing bowl. Put bmilk into the 6th mixing bowl. Put seltzer into the 6th mixing bowl. Put bmilk into the 6th mixing bowl. Serve with moist cake. Fold bmilk into the 1st mixing bowl. Fold sage into the 6th mixing bowl. Fold sage into the 6th mixing bowl. Put bmilk into the 4th mixing bowl. Remove seltzer from the 4th mixing bowl. Fold oregano into the 4th mixing bowl. Smell the oregano.

Fold bmilk into the 6th mixing bowl. 
Put bmilk into the 6th mixing bowl. 
Put fizzle into the 6th mixing bowl. 
Put bmilk into the 6th mixing bowl. 
Serve with moist cake. 
Fold bmilk into the 1st mixing bowl. 
Fold sage into the 6th mixing bowl. 
Fold sage into the 6th mixing bowl.
Put bmilk into the 4th mixing bowl. 
Remove fizzle from the 4th mixing bowl. 
Fold oregano into the 4th mixing bowl.
Crush the oregano.
 Clean the 1st mixing bowl. 
 Fold bmilk into the 6th mixing bowl. 
 Put bmilk into the 1st mixing bowl. 
 Refrigerate.
Grind until crushed.
Refrigerate.

Shuffle until smelled. Clean the 1st mixing bowl. Put milk into the 1st mixing bowl. Put vegetable oil into the 1st mixing bowl. Put sugar into the 1st mixing bowl. Put vinegar into the 1st mixing bowl. Put milk into the 1st mixing bowl. Stir the 1st mixing bowl for 5 minutes. Liquify contents of the 1st mixing bowl. Fold baking soda into the 3rd mixing bowl. Fold bmilk into the 6th mixing bowl. Put bmilk into the 6th mixing bowl. Put baking soda into the 6th mixing bowl. Put bmilk into the 6th mixing bowl. Serve with moist cake. Fold bmilk into the 1st mixing bowl. Fold sage into the 6th mixing bowl. Fold sage into the 6th mixing bowl. Put bmilk into the 4th mixing bowl. Remove baking soda from the 4th mixing bowl. Fold oregano into the 4th mixing bowl. Separate the oregano.

Refrigerate.

Part until separated. Put fizzle into the 6th mixing bowl. Serve with club soda. Stir the 1st mixing bowl for 1 minute. Stir the 1st mixing bowl for 7 minutes. Stir the 1st mixing bowl for 1 minute. Stir the 1st mixing bowl for 7 minutes. Stir the 1st mixing bowl for 5 minutes. Fold the oregano into the 1st mixing bowl. Fold the oregano into the 1st mixing bowl. Fold the oregano into the 1st mixing bowl. Fold the oregano into the 1st mixing bowl. Fold the oregano into the 1st mixing bowl. Refrigerate.

Moist cake.

Mods a number

Ingredients. 1 cup chocolate 70 g wheat flour 1 cup white chocolate chips 1 cup baking powder 105 g honey 5 cups syrup 1 g vanilla 1 g rosemary

Method. Fold chocolate into the 6th mixing bowl. Fold syrup into the 6th mixing bowl. Clean the 1st mixing bowl. Put chocolate into the 5th mixing bowl. Fold wheat flour into the 5th mixing bowl. Put white chocolate chips into the 5th mixing bowl. Remove white chocolate chips from the 5th mixing bowl. Fold baking powder into the 5th mixing bowl. Put baking powder into the 5th mixing bowl. Fold honey into the 5th mixing bowl. Sift the wheat flour.

Put honey into the 5th mixing bowl. 
Add white chocolate chips into the 5th mixing bowl.
Fold honey into the 5th mixing bowl.
Put honey into the 5th mixing bowl.
Remove syrup from the 5th mixing bowl.
Fold vanilla into the 5th mixing bowl.
Sprinkle the vanilla.
 Put white chocolate chips into the 5th mixing bowl.
 Remove white chocolate chips from the 5th mixing bowl.
 Fold rosemary into the 5th mixing bowl.
 Set aside.
Move until sprinkled. 
Recite the rosemary.
 Put white chocolate chips into the 5th mixing bowl.
 Remove white chocolate chips from the 5th mixing bowl.
 Fold honey into the 5th mixing bowl.
 Put baking powder into the 5th mixing bowl.
 Add white chocolate chips into the 5th mixing bowl.
 Fold baking powder into the 5th mixing bowl.
 Set aside.
Repeat until recited.
Put white chocolate chips into the 5th mixing bowl.
Fold rosemary into the 5th mixing bowl.

Shuffle the wheat flour until sifted. Put the baking powder into the 5th mixing bowl. Combine syrup into the 5th mixing bowl. Fold honey into the 5th mixing bowl. Put chocolate into the 5th mixing bowl. Remove honey from the 5th mixing bowl. Fold chocolate into the 5th mixing bowl. Put white chocolate chips into the 5th mixing bowl. Fold rosemary into the 5th mixing bowl. Siphon chocolate.

Put white chocolate chips into the 5th mixing bowl.
Remove white chocolate chips from the 5th mixing bowl.
Fold rosemary into the 5th mixing bowl.
Set aside. 

Gulp until siphoned. Quote the rosemary.

Put syrup into the 5th mixing bowl.
Fold chocolate into the 5th mixing bowl.
Set aside. 

Repeat until quoted. Put chocolate into the 1st mixing bowl. Refrigerate.</lang>

Clay

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

}</lang>

CLIPS

<lang 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)
   )
   (printout t crlf)
 )

)</lang>

Clojure

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

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

:else x))

    (range 1 101))</lang>

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

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

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

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

CMake

<lang cmake>foreach(i RANGE 1 100)

 math(EXPR off3 "${i} % 3")
 math(EXPR off5 "${i} % 5")
 if(NOT off3 AND NOT off5)
   message(FizzBuzz)
 elseif(NOT off3)
   message(Fizz)
 elseif(NOT off5)
   message(Buzz)
 else()
   message(${i})
 endif()

endforeach(i)</lang>

CoffeeScript

<lang CoffeeScript>for i in [1..100]

 if i % 15 is 0
   console.log "FizzBuzz"
 else if i % 3 is 0
   console.log "Fizz"
 else if i % 5 is 0
   console.log "Buzz"
 else
   console.log i

</lang>

Common Lisp

<lang lisp>(defun fizzbuzz ()

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

(defun fizzbuzz ()

 (loop for x from 1 to 100 do
   (format t "~&~{~A~}"
     (or (append (when (zerop (mod x 3)) '("Fizz"))
                 (when (zerop (mod x 5)) '("Buzz")))
         (list x)))))</lang>

D

<lang d>import std.stdio: writeln;

// with if-else void fizzBuzz(int n) {

   foreach (i; 1 .. n+1)
       if (!(i % 15))
           writeln("FizzBuzz");
       else if (!(i % 3))
           writeln("Fizz");
       else if (!(i % 5))
           writeln("Buzz");
       else
           writeln(i);

}

// with switch case void fizzBuzzSwitch(int n) {

   foreach (i; 1 .. n+1)
       switch(i % 15) {
           case 0:
               writeln("FizzBuzz"); break;        
           case 3, 6, 9, 12:
               writeln("Fizz"); break;
           case 5, 10:
               writeln("Buzz"); break;
           default:
               writeln(i);
       }

}

void main() {

   fizzBuzz(100);
   writeln();
   fizzBuzzSwitch(100);

}</lang>

dc

Translation of: bc

<lang dc>[[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 

]sL 1 si [i = 1]sz 0 0 =L [enter Loop]sz</lang>

Delphi

<lang Delphi>program FizzBuzz;

{$APPTYPE CONSOLE}

uses SysUtils;

var

 i: Integer;
 lOutput: string;

begin

 for i := 1 to 100 do
 begin
   lOutput := ;
   if i mod 3 = 0 then
     lOutput := 'Fizz';
   if i mod 5 = 0 then
     lOutput := lOutput + 'Buzz';
   if lOutput =  then
     lOutput := IntToStr(i);
   Writeln(lOutput);
 end;

end.</lang>

DWScript

<lang delphi>var i : Integer;

for i := 1 to 100 do begin

  if i mod 15 = 0 then
     PrintLn('FizzBuzz')
  else if i mod 3 = 0 then
     PrintLn('Fizz')
  else if i mod 5 = 0 then
     PrintLn('Buzz')
  else PrintLn(i);

end;</lang>

E

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

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

Erlang

<lang erlang>fizzbuzz() ->

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

Euphoria

Works with: Euphoria 4.0.0

This is based on the VBScript example. <lang Euphoria> include std/utils.e

function fb( atom n ) sequence fb if remainder( n, 15 ) = 0 then fb = "FizzBuzz" elsif remainder( n, 5 ) = 0 then fb = "Fizz" elsif remainder( n, 3 ) = 0 then fb = "Buzz" else fb = sprintf( "%d", n ) end if return fb end function

function fb2( atom n ) return iif( remainder(n, 15) = 0, "FizzBuzz", iif( remainder( n, 5 ) = 0, "Fizz", iif( remainder( n, 3) = 0, "Buzz", sprintf( "%d", n ) ) ) ) end function

for i = 1 to 30 do printf( 1, "%s ", { fb( i ) } ) end for

puts( 1, "\n" )

for i = 1 to 30 do printf( 1, "%s ", { fb2( i ) } ) end for

puts( 1, "\n" )</lang>

Factor

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

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

MAIN: main</lang>

F#

<lang fsharp>

  1. light

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

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

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

Falcon

<lang falcon>for i in [1:101]

   switch i % 15
   case 0        : > "FizzBuzz"
   case 5,10     : > "Buzz"
   case 3,6,9,12 : > "Fizz"
   default       : > i
   end

end</lang>

FALSE

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

Fantom

<lang fantom> class FizzBuzz {

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

} </lang>

Forth

table-driven

<lang forth>: fizz ( n -- ) drop ." Fizz" ;

buzz ( n -- ) drop ." Buzz" ;
fb ( n -- ) drop ." FizzBuzz" ;
vector create does> ( n -- )
 over 15 mod cells + @ execute ;

vector .fizzbuzz

 ' fb   , ' . ,    ' . ,
 ' fizz , ' . ,    ' buzz ,
 ' fizz , ' . ,    ' . ,
 ' fizz , ' buzz , ' . ,
 ' fizz , ' . ,    ' . ,</lang>

or the classic approach

<lang forth>: .fizzbuzz ( n -- )

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

100 zz</lang>

the well factored approach

SYNONYM is a Forth200x word.

<lang forth>SYNONYM NOT INVERT \ Bitwise boolean not

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

FizzBuzz</lang>

Fortran

In ANSI FORTRAN 77 or later use structured IF-THEN-ELSE (example uses some ISO Fortran 90 features): <lang fortran>program fizzbuzz_if

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

end program fizzbuzz_if</lang>

In ISO Fortran 90 or later use SELECT-CASE statement: <lang fortran>program fizzbuzz_select

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

GAP

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

Go

<lang go>package main import "fmt"

func main() {

   for i := 1; i <= 100; i++ {
       switch {
       case (i%3==0) && (i%5==0):
           fmt.Println("FizzBuzz")
       case i%3==0:
           fmt.Println("Fizz")
       case i%5==0:
           fmt.Println("Buzz")
       default: 
           fmt.Println(i)
       }
   }

}</lang>

Gosu

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

} </lang>

One liner version (I added new lines to better readability but when you omit them it's one liner): <lang gosu>// note that compiler reports error (I don't know why) but still it's working for (i in 1..100) {

   print(i % 5 == 0 ? i % 3 == 0 ? "FizzBuzz" : "Buzz" : i % 3 == 0 ? "Fizz" : i)

} </lang>

Groovy

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

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

}</lang>

Haskell

Variant directly implementing the specification:

<lang haskell>main = mapM_ (putStrLn . fizzbuzz) [1..100]

fizzbuzz x

   | x `mod` 15 == 0 = "FizzBuzz"
   | x `mod`  3 == 0 = "Fizz"
   | x `mod`  5 == 0 = "Buzz"
   | otherwise = show x

</lang>

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

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

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

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

HicEst

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

ENDDO</lang> Alternatively: <lang hicest>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() string

ENDDO</lang>

Icon and Unicon

<lang icon># straight-forward modulo tester procedure 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</lang>

<lang icon># idiomatic modulo tester, 1st alternative procedure main()

   every i := 1 to 100 do
       write((i % 15 = 0 & "FizzBuzz") | (i % 5 = 0 & "Buzz") | (i % 3 = 0 & "Fizz") | i)

end</lang>

<lang icon># idiomatic modulo tester, 2nd alternative procedure main()

   every i := 1 to 100 do
       write(case 0 of {
                i % 15 : "FizzBuzz"
                i % 5  : "Buzz"
                i % 3  : "Fizz"
                default: i
       })

end</lang>

<lang icon># straight-forward buffer builder procedure 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</lang>

<lang icon># idiomatic buffer builder, 1st alternative procedure main()     every i := 1 to 100 do         write("" ~== (if i % 3 = 0 then "Fizz" else "") || (if i % 5 == 0 then "Buzz" else "") | i) end</lang>

<lang icon># idiomatic buffer builder, 2nd alternative procedure 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</lang>

Inform 7

<lang inform7>Home is a room.

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

Io

Here's one way to do it:

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

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

)</lang>

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

<lang io>a := 0; b := 0 for(n, 1, 100,

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

)</lang>

And here is another more idiomatic version:

<lang Io>for (n, 1, 100,

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

)</lang>

Ioke

<lang ioke>(1..100) each(x,

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

)</lang>

Iptscrae

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

FizzBuzz in Iptscrae

1 a = {

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

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

J

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

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

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

Solution 2 (has taste of table-driven template programming) <lang j>CRT0=: 2 : ' (, 0 = +./)@(0 = m | ]) ;@# n , <@": ' NB. Rather (, 0 = +./) than (, +:/) because designed for NB. 3 5 7 CRT0 (;:'Chinese Remainder Period') "0 >: i. */3 5 7 FizzBuzz=: 3 5 CRT0 (;:'Fizz Buzz')

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

Solution 3 (depends on an obsolete feature of @ in f`g`h@p) <lang j>'`f b fb' =: ('Fizz'"_) ` ('Buzz'"_) ` (f , b) '`cm3 cm5 cm15'=: (3&|) ` (5&|) ` (15&|) (0&=@) FizzBuzz=: ": ` f @. cm3 ` b @. cm5 ` fb @. cm15 NB. also: FizzBuzz=: ": ` f @. cm3 ` b @. cm5 ` (f,b) @. (cm3 *. cm5)

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

Java

If/else ladder

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

Concatenation

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

Ternary operator

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

Recursive

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

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

}</lang>

Alternative Recursive

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

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

}</lang>

Using an array

<lang java>class FizzBuzz {

 public static void main( String [] args ) {
   for( int i = 1 ; i <= 100 ; i++ ) {
     System.out.println( new String[]{ i+"", "Fizz", "Buzz", "FizzBuzz" }[ ( i%3==0?2:0 ) + ( i%5==0?1:0 )  ]);
   }
 }

}</lang>

JavaScript

Works with: NJS version 0.2.5

<lang javascript>for (var i = 1; i <= 100; i++) {

 if (i % 15 == 0) {
   print("FizzBuzz");
 } else if (i % 3 == 0) {
   print("Fizz");
 } else if (i % 5 == 0) {
   print("Buzz");
 } else {
   print(i);
 }

}

// ------------------ // functional version // ------------------ (function (n) {

    var r = [];

    while (n--) {
        r.push(n + 1);
    }

    return r.reverse();
})(100).map(function (n) {
    return !(n % 15) ?
        'FizzBuzz' :
        !(n % 3) ?
            'Fizz' :
            !(n % 5) ?
                'Buzz' :
                n;
}).join('\r\n');

</lang>

Alternative Version (one-liner)

<lang javascript>for (var i = 1; i < 101; i += 1) print(((i % 3 === 0 ? 'Fizz' : ) + (i % 5 === 0 ? 'Buzz' : ) || i) + '\n');</lang>

K

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

Liberty BASIC

<lang lb>for i = 1 to 100

   select case
       case i mod 15 = 0
           print "FizzBuzz"
       case i mod 3 = 0
           print "Fizz"
       case i mod 5 = 0
           print "Buzz"
       case else
           print i
   end select

next i</lang>

<lang logo>to fizzbuzz :n

 output cond [ [[equal? 0 modulo :n 15] "FizzBuzz]
               [[equal? 0 modulo :n  5] "Buzz]
               [[equal? 0 modulo :n  3] "Fizz]
               [else :n] ]

end

repeat 100 [print fizzbuzz #]</lang>

Lua

If/else Ladder

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

Concatenation

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

M4

<lang M4>define(`for',

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

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

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

')</lang>

make

Works with: BSD make
Library: jot

<lang make>MOD3 = 0 MOD5 = 0 ALL != jot 100

all: say-100

.for NUMBER in $(ALL)

MOD3 != expr \( $(MOD3) + 1 \) % 3; true MOD5 != expr \( $(MOD5) + 1 \) % 5; true

. if "$(NUMBER)" > 1 PRED != expr $(NUMBER) - 1 say-$(NUMBER): say-$(PRED) . else say-$(NUMBER): . endif . if "$(MOD3)$(MOD5)" == "00" @echo FizzBuzz . elif "$(MOD3)" == "0" @echo Fizz . elif "$(MOD5)" == "0" @echo Buzz . else @echo $(NUMBER) . endif

.endfor</lang>

Mathematica

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

MATLAB

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

<lang MATLAB>function fizzBuzz()

   for i = (1:100)
       
       if mod(i,3) == 0
          fprintf('Fizz')
       end
           
       if mod(i,5) == 0
          fprintf('Buzz')
       end
       if not((mod(i,3) == 0) || (mod(i,5) == 0))
          fprintf(num2str(i)) 
       end
       
       fprintf(' ')
   end
   fprintf('\n');    

end</lang>


MAXScript

<lang maxscript>for i in 1 to 100 do (

   case of
   (
       (mod i 15 == 0): (print "FizzBuzz")
       (mod i 5 == 0):  (print "Buzz")
       (mod i 3 == 0):  (print "Fizz")
       default:         (print i)
   )

)</lang>

Metafont

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

Mirah

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

  1. 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
   end

end</lang>

MMIX

<lang mmix>t IS $255 Ja IS $127

      LOC Data_Segment

data 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 subroutine printnum LOC @

      OR   $1,$0,0
      SETL $2,buffer+64
      ADDU $2,$2,data
      XOR  $3,$3,$3
      STBU $3,$2,1

loop 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 = 1 1H 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 i

3H BP $2,5F  % skip if Fizz was taken

      GO   Ja,printnum    % print i

5H ADDU t,data,nl

      TRAP 0,Fputs,StdOut % print newline
      ADDU $0,$0,1
      JMP  1B             % repeat for next i

4H XOR t,t,t

      TRAP 0,Halt,0       % exit(0)</lang>

Modula-3

<lang modula3>MODULE Fizzbuzz EXPORTS Main;

IMPORT IO;

BEGIN

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

END Fizzbuzz.</lang>

MUMPS

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

</lang>

Nemerle

The naive approach: <lang Nemerle>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))")
   }

}</lang> A much slicker approach is posted here

Oberon-2

<lang oberon2>MODULE FizzBuzz;

  IMPORT Out;
  VAR i: INTEGER;

BEGIN

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

END FizzBuzz.</lang>

NetRexx

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

end </lang>

Nimrod

Translation of: Python

<lang nimrod>for i in 1..100:

 if i mod 15 == 0:
   echo("FizzBuzz")
 elif i mod 3 == 0:
   echo("Fizz")
 elif i mod 5 == 0:
   echo("Buzz")
 else:
   echo(i)</lang>

Without Modulus

<lang nimrod>var messages = @["", "Fizz", "Buzz", "FizzBuzz"] var acc = 810092048 for i in 1..100:

 var c = acc and 3
 echo(if c == 0: $i else: messages[c])
 acc = acc shr 2 or c shl 28</lang>

Objeck

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

} </lang>

OCaml

<lang ocaml>let output x =

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

let _ =

 for i = 1 to 100 do print_endline (output i) done</lang>

Octave

<lang octave>for i = 1:100

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

endfor</lang>

Oz

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

in

 for I in 1..100 do
    {Show {FizzBuzz I}}
 end</lang>

PARI/GP

<lang parigp>{for(n=1,100,

 print(if(n%3,
   if(n%5,
     n
   ,
     "Buzz"
   )
 ,
   if(n%5,
     "Fizz"
   ,
     "FizzBuzz"
   )
 ))

)}</lang>

Pascal

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

Perl

<lang perl>foreach (1 .. 100) {

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

};</lang>

More concisely:

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

Perl 6

Works with: Rakudo Star version 2010-08

Most straightforwardly:

<lang perl6>for 1 .. 100 {

   when $_ %% (3 & 5) { say 'FizzBuzz'; }
   when $_ %% 3       { say 'Fizz'; }
   when $_ %% 5       { say 'Buzz'; }
   default            { .say; }

}</lang>

Most concisely:

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

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

<lang perl6>.say for

 (( xx 2, 'Fizz') xx * Z~
  ( xx 4, 'Buzz') xx *) Z||
 1 .. 100;</lang>

PHP

if/else ladder approach

<lang php><?php for ($i = 1; $i <= 100; $i++) {

   if (!($i % 15))
       echo "FizzBuzz\n";
   else if (!($i % 3))
       echo "Fizz\n";
   else if (!($i % 5))
       echo "Buzz\n";
   else
       echo "$i\n";

} ?></lang>

concatenation approach

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

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

<lang php><?php for ( $i = 1; $i <= 100; ++$i ) {

    $str = "";
    if (!($i % 3 ) )
         $str .= "Fizz";
    if (!($i % 5 ) )
         $str .= "Buzz";
    if ( empty( $str ) )
         $str = $i;
    echo $str . "\n";

} ?></lang>

One Liner Approach

<lang php> <?php for($i = 1; $i <= 100 and print(($i % 15 ? $i % 5 ? $i % 3 ? $i : 'Fizz' : 'Buzz' : 'FizzBuzz') . "\n"); ++$i); </lang>

PicoLisp

We could simply use 'at' here: <lang PicoLisp>(for N 100

  (prinl
     (or (pack (at (0 . 3) "Fizz") (at (0 . 5) "Buzz")) N) ) )</lang>

Or do it the standard way: <lang PicoLisp>(for N 100

  (prinl
     (cond
        ((=0 (% N 15)) "FizzBuzz")
        ((=0 (% N 3)) "Fizz")
        ((=0 (% N 5)) "Buzz")
        (T N) ) ) )</lang>

Pike

<lang pike>int main(){

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

}</lang>

PIR

Works with: Parrot version tested with 2.4.0

<lang pir>.sub main :main

 .local int f
 .local int mf
 .local int skipnum
 f = 1

LOOP:

 if f > 100 goto DONE
 skipnum = 0
 mf = f % 3
 if mf == 0 goto FIZZ

FIZZRET:

 mf = f % 5
 if mf == 0 goto BUZZ

BUZZRET:

 if skipnum > 0 goto SKIPNUM
 print f

SKIPNUM:

 print "\n"
 inc f 
 goto LOOP
 end

FIZZ:

 print "Fizz"
 inc skipnum
 goto FIZZRET
 end

BUZZ:

 print "Buzz"
 inc skipnum
 goto BUZZRET
 end

DONE:

 end

.end</lang>

PL/I

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

Pop11

<lang pop11>lvars str; for i from 1 to 100 do

 if i rem 15 = 0 then
   'FizzBuzz' -> str;
 elseif i rem 3 = 0 then
   'Fizz' -> str;
 elseif i rem 5 = 0 then
   'Buzz' -> str;
 else
    >< i -> str;
 endif;
 printf(str, '%s\n');

endfor;</lang>

PostScript

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

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

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

PowerShell

Straightforward, looping

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

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

}</lang>

Pipeline, Switch

<lang powershell>$txt=$null 1..100 | ForEach-Object {

   switch ($_) {
       { $_ % 3 -eq 0 }  { $txt+="Fizz" }
       { $_ % 5 -eq 0 }  { $txt+="Buzz" }
       $_                { if($txt) { $txt } else { $_ }; $txt=$null }
   }

}</lang>

Concatenation

Translation of: C#

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

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

}</lang>

Prolog

Works with: SWI Prolog version 4.8.0

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

<lang prolog>fizzbuzz :-

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

print_item(X) :-

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

More conventional:

<lang prolog> fizzbuzz(X) :- 0 is X mod 15, write('FizzBuzz'). fizzbuzz(X) :- 0 is X mod 3, write('Fizz'). fizzbuzz(X) :- 0 is X mod 5, write('Buzz'). fizzbuzz(X) :- write(X).

dofizzbuzz :- foreach(between(1, 100, X), (fizzbuzz(X),nl)). </lang>

Protium

Variable-length padded English dialect <lang html><# 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|...</#> </#></lang>

Fixed-length English dialect <lang html><@ 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|...</@> </@> </lang>

PureBasic

<lang purebasic>OpenConsole() For x = 1 To 100

 If x%15 = 0
   PrintN("FizzBuzz")
 ElseIf x%3 = 0
   PrintN("Fizz")
 ElseIf x%5 = 0
   PrintN("Buzz")
 Else
   PrintN(Str(x))
 EndIf

Next Input()</lang>

Python

<lang python>for i in xrange(1, 101):

   if i % 15 == 0:
       print "FizzBuzz"
   elif i % 3 == 0:
       print "Fizz"
   elif i % 5 == 0:
       print "Buzz"
   else:
       print i</lang>

And a shorter, but less clear version, using a list comprehension and logical expressions: <lang python>for i in range(1, 101):

   words = [word for n, word in ((3, 'Fizz'), (5, 'Buzz')) if not i % n]
   print .join(words) or i</lang>

Without modulus

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

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

R

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

Or, (ab)using the vector recycling rule,

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

RapidQ

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

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

NEXT i</lang>

Raven

<lang raven>100 each 1 + as n

 
 n 3 mod 0 = if 'Fizz' cat
 n 5 mod 0 = if 'Buzz' cat
 dup empty if drop n
 say</lang>

REBOL

Shortest implementation:

<lang REBOL>repeat i 100 [case/all [i // 3 = 0 [print"fizz"] i // 5 = 0 [print "buzz"] 1 [print i]]]</lang>

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

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

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

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

Here are two examples by Nick Antonaccio.

<lang REBOL>repeat i 100 [

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

]

And minimized version

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

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

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

Retro

This is a port of some Forth code.

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

It's cleaner to use quotes and combinators though:

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

REXX

version 1

<lang rexx>

 do j=1 to 100
 z=j
 if j//(3*5)==0 then z='FizzBuzz'
 if j//5    ==0 then z='Fuzz'
 if j//3    ==0 then z='Fizz'
 say z
 end

</lang> Output:

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

version 2

<lang rexx>

 do j=1 for 100
   select
   when j//15==0 then say 'FizzBuzz'
   when j//5==0  then say 'Fuzz'
   when j//3==0  then say 'Fizz'
   otherwise          say right(j,4)
   end
 end

</lang> Output:

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

Ruby

<lang ruby>1.upto(100) do |n|

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

end</lang>

A bit more straightforward: <lang ruby>1.upto(100) do |n|

 if (n % 15).zero?
   puts "FizzBuzz"
 elsif (n % 5).zero?
   puts "Buzz"
 elsif (n % 3).zero?
   puts "Fizz"
 else
   puts n
 end

end</lang>

Monkeypatch example:

<lang ruby>class Integer

 def fizzbuzz
   returnval=
   returnval += "Fizz" if (self % 3).zero?
   returnval += "Buzz" if (self % 5).zero?
   return returnval.empty? ? self : returnval
 end

end

puts (1..100).collect { |x| x.fizzbuzz }.join("\n")</lang>

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

Sather

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

Scala

<lang scala>(1 to 100) foreach {

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

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

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

}) foreach println</lang>

geeky over-generalized solution: <lang scala>def replaceMultiples(x: Int, rs: (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(n: Int) =

 replaceMultiples(n, 3 -> "Fizz", 5 -> "Buzz") fold ((_ toString), identity)

1 to 100 map fizzbuzz foreach println</lang>

Scheme

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

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

Seed7

<lang seed7>$ include "seed7_05.s7i";

const proc: main is func

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

Slate

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

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

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

Smalltalk

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

<lang smalltalk>Integer extend [

   fizzbuzz [
       | fb |
       fb := '%<Fizz|>1%<Buzz|>2' % {
           self \\ 3 == 0.  self \\ 5 == 0 }.
       ^fb isEmpty ifTrue: [ self ] ifFalse: [ fb ]
   ]

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

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

                       ifFalse: [Transcript show: n].

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

SNOBOL4

Merely posting a solution by Daniel Lyons

<lang snobol4> I = 1 LOOP FIZZBUZZ = ""

       EQ(REMDR(I, 3), 0)              :F(TRY_5)
       FIZZBUZZ = FIZZBUZZ "FIZZ"

TRY_5 EQ(REMDR(I, 5), 0) :F(DO_NUM)

       FIZZBUZZ = FIZZBUZZ "BUZZ"      

DO_NUM IDENT(FIZZBUZZ, "") :F(SHOW)

       FIZZBUZZ = I

SHOW OUTPUT = FIZZBUZZ

       I = I + 1
       LE(I, 100)                      :S(LOOP)

END</lang>


SNUSP

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

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

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

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

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

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

SQL

<lang sql> DROP TABLE fizzbuzz; CREATE TABLE fizzbuzz(i int, fizz string, buzz string); INSERT INTO fizzbuzz VALUES(1,"",""); INSERT INTO fizzbuzz SELECT i + (SELECT max(i) FROM fizzbuzz), fizz, buzz FROM fizzbuzz; INSERT INTO fizzbuzz SELECT i + (SELECT max(i) FROM fizzbuzz), fizz, buzz FROM fizzbuzz; INSERT INTO fizzbuzz SELECT i + (SELECT max(i) FROM fizzbuzz), fizz, buzz FROM fizzbuzz; INSERT INTO fizzbuzz SELECT i + (SELECT max(i) FROM fizzbuzz), fizz, buzz FROM fizzbuzz; INSERT INTO fizzbuzz SELECT i + (SELECT max(i) FROM fizzbuzz), fizz, buzz FROM fizzbuzz; INSERT INTO fizzbuzz SELECT i + (SELECT max(i) FROM fizzbuzz), fizz, buzz FROM fizzbuzz; INSERT INTO fizzbuzz SELECT i + (SELECT max(i) FROM fizzbuzz), fizz, buzz FROM fizzbuzz; DROP TABLE lookup; CREATE TABLE lookup (fizzy, buzzy, rem); INSERT INTO lookup VALUES("fizz", "buzz", 1); SELECT

(SELECT i FROM lookup WHERE rem = (i%3<>0)&(i%5<>0)),
(SELECT fizzy FROM lookup WHERE rem = (i%3=0)),
(SELECT buzzy FROM lookup WHERE rem = (i%5=0))
 FROM fizzbuzz WHERE i <= 100;

</lang>

Alternate solution by Daniel Lyons (PostgreSQL specific):

<lang sql> SELECT i, fizzbuzz

 FROM 
   (SELECT i, 
           CASE 
             WHEN i % 15 = 0 THEN 'FizzBuzz' 
             WHEN i %  5 = 0 THEN 'Buzz' 
             WHEN i %  3 = 0 THEN 'Fizz' 
             ELSE NULL 
           END AS fizzbuzz 
      FROM generate_series(1,100) AS i) AS fb 
WHERE fizzbuzz IS NOT NULL;

</lang>

Another alternative solution based on recursive Common Table Expressions (MSSQL 2005+):

<lang sql> WITH nums (n, fizzbuzz ) AS ( SELECT 1, CONVERT(nvarchar, 1) UNION ALL SELECT (n + 1) as n1, CASE WHEN (n + 1) % 15 = 0 THEN 'FizzBuzz' WHEN (n + 1) % 3 = 0 THEN 'Fizz' WHEN (n + 1) % 5 = 0 THEN 'Buzz' ELSE CONVERT(nvarchar, (n + 1)) END FROM nums WHERE n < 100 ) SELECT n, fizzbuzz FROM nums ORDER BY n ASC OPTION ( MAXRECURSION 100 ) </lang>

Here is the Oracle PL/SQL solution: <lang sql> declare

 v_count integer;
 

begin

 for v_count in 1..100 loop
   if(mod(v_count, 15) = 0) then
     dbms_output.put_line('Fizz Buzz');
   elsif(mod(v_count, 3) = 0) then
     dbms_output.put_line('Fizz');
   elsif(mod(v_count, 5) = 0) then
     dbms_output.put_line('Buzz');
   else
     dbms_output.put_line(v_count);
   end if;
 end loop;

end; </lang>

Standard ML

<lang sml>fun output x =

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

val () = let

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

in

 aux 1

end</lang>

Tcl

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

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

} fizzbuzz 100</lang>

TUSCRIPT

<lang tuscript> $$ MODE TUSCRIPT LOOP n=1,100 mod=MOD (n,15) SELECT mod CASE 0 PRINT n," FizzBuzz" CASE 3,6,9,12 PRINT n," Fizz" CASE 5,10 PRINT n," Buzz" DEFAULT PRINT n ENDSELECT ENDLOOP </lang>

UNIX Shell

This solution should work with any Bourne-compatible shell. <lang bash>i=1 while expr $i '<=' 100 >/dev/null; do w=false expr $i % 3 = 0 >/dev/null && { printf Fizz; w=true; } expr $i % 5 = 0 >/dev/null && { printf Buzz; w=true; } if $w; then echo; else echo $i; fi i=`expr $i + 1` done</lang>

The other solutions work with fewer shells.


The next solution requires $(( )) arithmetic expansion, which is in every POSIX shell; but it also requires the seq(1) command which is not part of some systems. (If your system misses seq(1), but it has BSD jot(1), then change `seq 1 100` to `jot 100`.)

<lang bash>for n in `seq 1 100`; do

 if [ $((n % 15)) = 0 ]; then
   echo FizzBuzz
 elif [ $((n % 3)) = 0 ]; then
   echo Fizz
 elif [ $((n % 5)) = 0 ]; then
   echo Buzz
 else
   echo $n
 fi

done</lang>


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

Works with: pdksh version 5.2.14

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

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

done</lang>


A version using concatenation:

Works with: bash version 3

<lang bash>for ((n=1; n<=100; n++)) do

 fb=
 [ $(( n % 3 )) -eq 0 ] && fb="${fb}Fizz"
 [ $(( n % 5 )) -eq 0 ] && fb="${fb}Buzz"
 [ -n "${fb}" ] && echo "${fb}" || echo "$n"

done</lang>


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

Works with: bash version 4

<lang bash>command_not_found_handle () {

 local Fizz=3 Buzz=5
 [ $(( $2 % $1 )) -eq 0 ] && echo -n $1 && [ ${!1} -eq 3 ]

}

for i in {1..100} do

 Fizz $i && ! Buzz $i || echo -n $i
 echo

done</lang>

Ursala

<lang Ursala>#import std

  1. import nat

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

  1. show+

main = fizzbuzz*t iota 101</lang>

V

<lang v>[fizzbuzz

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

Second try

(a compiler for fizzbuzz)

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

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

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

And apply it <lang v>100 seq [

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

the first one is much better :)

VBScript

Implementation

The EEF does eager evaluation. I'm still trying to figure out a lazy evaluation method using Eval(). One day ...

In the meantime, converting that to VB6 would mean using VB6's IIF() which would run a tad faster.

<lang vb> 'using the IF/ELSEIF ladder function fb( n ) if n mod 15 = 0 then fb = "FizzBuzz" elseif n mod 5 = 0 then fb = "Fizz" elseif n mod 3 = 0 then fb = "Buzz" else fb = n end if end function

'the Mexican IF function eef( b, p1, p2 ) if b then eef = p1 else eef = p2 end if end function

'using the Mexican IF function fb2( n ) fb2 = eef( n mod 15 = 0, "FizzBuzz", eef( n mod 5 = 0, "Fizz", eef( n mod 3 = 0, "Buzz", n ) ) ) end function

</lang>

Invocation

<lang vb> for i = 1 to 16 wscript.stdout.write fb(i) & " " next wscript.echo

for i = 1 to 16 wscript.stdout.write fb2(i) & " " next wscript.echo

</lang>

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

Visual Basic .NET

Platform: .NET

Works with: Visual Basic .NET version 9.0+

<lang vbnet>Sub Main()

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

End Sub</lang>

Whitespace

This Whitespace solution is actually generated by Lisp.

<lang whitespace>

























































</lang>

Here is a (partly) annotated version, using 's' for space, 't' for tab and 'n' for newline:

<lang pseudocode> ss stn [push +1] nss sttsttn [mark +11011=loop-start-label] sns [dup] ss sttsstssn [push +1100100=100] snt [swap] tsst [sub] ntt stttssn [jneg +11100=loop-end-label] sns [dup] ss sttttn [push +1111=15] tstt [mod] nts stttstn [jz +11101=if-mod15-label] nsn sttttsn [jmp +11110=after-mod15-label] nss stttstn [mark +11101=if-mod15-label] ss stsssttsn [push +1000110='F'] tnss [print-char] ss sttstsstn [push +1101001='i'] tnss [print-char] ss sttttstsn [push +1111010='z'] tnss [print-char] ss sttttstsn [push +1111010='z'] tnss [print-char] ss stsssstsn [push +1000010='B'] tnss [print-char] ss stttststn [push +1110101='u'] tnss [print-char] ss sttttstsn [push +1111010='z'] tnss [print-char] ss sttttstsn [push +1111010='z'] tnss [print-char] nsn stttttn [jmp +11111=cond-end-label] nss sttttsn [mark +11110=after-mod15-label] sns [dup] ss sttn [push +11=3] tstt [mod] ... (same as above, just for 3 (Fizz) and 5 (Buzz)) ... nss stttttn [mark +11111=cond-end-label] ss ststsn [push +1010=<Newline>] tnss [print-char] ss stn [push +1=1] tsss [add] nsn sttsttn [jmp +11011=loop-start-label] nss stttssn [mark +11100=loop-end-label] snn [drop] nnn [quit] </lang>

Yorick

Iterative solution

<lang yorick>for(i = 1; i <= 100; i++) {

   if(i % 3 == 0)
       write, format="%s", "Fizz";
   if(i % 5 == 0)
       write, format="%s", "Buzz";
   if(i % 3 && i % 5)
       write, format="%d", i;
   write, "";

}</lang>

Vectorized solution

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