FizzBuzz: Difference between revisions
Content deleted Content added
(137 intermediate revisions by 65 users not shown) | |||
Line 9:
But:
:* for multiples of three, print '''Fizz'''
:* for multiples of five, print '''Buzz'''
:* for multiples of both three and five, print '''FizzBuzz'''
Line 25:
{{trans|Python3: Simple}}
<
I i % 15 == 0
print(‘FizzBuzz’)
Line 33:
print(‘Buzz’)
E
print(i)</
=={{header|360 Assembly}}==
Line 51:
=={{header|8th}}==
<
with: n
Line 77:
' fizzbuzz 1 100 loop
cr bye
</syntaxhighlight>
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<syntaxhighlight lang="aarch64 assembly">
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program FizzBuzz64.s */
Line 176:
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
=={{header|ABAP}}==
===Impure Functional 1===
{{works with|ABAP|7.4 SP05 or Above only}}
<
tab = VALUE #(
Line 193:
cl_demo_output=>write( tab ).
cl_demo_output=>display( ).</
===Impure Functional 2===
{{works with|ABAP|7.4 SP05 or Above only}}
<
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 ) ) ) ).</
=={{header|ABC}}==
<syntaxhighlight lang="ABC">HOW TO RETURN fizzbuzz num:
PUT "" IN result
PUT {[3]: "Fizz"; [5]: "Buzz"} IN divwords
FOR div IN keys divwords:
IF num mod div=0:
PUT result^divwords[div] IN result
IF result="":
PUT num>>0 IN result
RETURN result
FOR i IN {1..100}:
WRITE fizzbuzz i/</syntaxhighlight>
=={{header|ACL2}}==
<
(declare (xargs :measure (nfix (- 100 i))))
(prog2$
Line 215 ⟶ 229:
(fizzbuzz-r (1+ i)))))
(defun fizzbuzz () (fizzbuzz-r 1))</
=={{header|Action!}}==
<
BYTE i,d3,d5
Line 239 ⟶ 253:
IF d5=5 THEN d5=0 FI
OD
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/FizzBuzz.png Screenshot from Atari 8-bit computer]
Line 252 ⟶ 266:
=={{header|ActionScript}}==
The [[ActionScript]] solution works just like the [[FizzBuzz#JavaScript|JavaScript]] solution (they share the [[ECMAScript]] specification). The difference is that ActionScript has the ''trace'' command to write out to a console.
<
if (i % 15 == 0)
trace('FizzBuzz');
Line 261 ⟶ 275:
else
trace(i);
}</
=={{header|Ada}}==
<
procedure Fizzbuzz is
Line 279 ⟶ 293:
end if;
end loop;
end Fizzbuzz;</
=={{header|Agda}}==
<syntaxhighlight lang="agda">
module FizzBuzz where
open import Agda.Builtin.IO using (IO)
open import Agda.Builtin.Unit renaming (⊤ to Unit)
open import Data.Bool using (Bool ; false ; true ; if_then_else_)
open import Data.Nat using (ℕ ; zero ; suc ; _≡ᵇ_ ; _%_)
open import Data.Nat.Show using (show)
open import Data.List using (List ; [] ; _∷_ ; map)
open import Data.String using (String ; _++_ ; unlines)
postulate putStrLn : String -> IO Unit
{-# FOREIGN GHC import qualified Data.Text as T #-}
{-# COMPILE GHC putStrLn = putStrLn . T.unpack #-}
fizz : String
fizz = "Fizz"
buzz : String
buzz = "Buzz"
_isDivisibleBy_ : (n : ℕ) -> (m : ℕ) -> Bool
n isDivisibleBy zero = false
n isDivisibleBy (suc k) = ((n % (suc k)) ≡ᵇ 0)
getTerm : (n : ℕ) -> String
getTerm n =
if (n isDivisibleBy 15) then (fizz ++ buzz)
else if (n isDivisibleBy 3) then fizz
else if (n isDivisibleBy 5) then buzz
else (show n)
range : (a : ℕ) -> (b : ℕ) -> List (ℕ)
range k zero = []
range k (suc m) = k ∷ (range (suc k) m)
getTerms : (n : ℕ) -> List (String)
getTerms n = map getTerm (range 1 n)
fizzBuzz : String
fizzBuzz = unlines (getTerms 100)
main : IO Unit
main = putStrLn fizzBuzz
</syntaxhighlight>
=={{header|ALGOL 68}}==
<
FOR i TO 100 DO
printf(($gl$,
Line 296 ⟶ 364:
))
OD
)</
or simply:
<
or only testing for divisibility by 3 and 5 (AND does not shortcut in Algol 68), as suggested in the [[#NewLISP]] second sample:
<syntaxhighlight>
FOR i TO 100 DO
IF IF i MOD 3 = 0 THEN print( "Fizz" ); FALSE ELSE TRUE FI
AND IF i MOD 5 = 0 THEN print( "Buzz" ); FALSE ELSE TRUE FI
THEN
print( ( whole( i, 0 ) ) )
FI;
print( ( newline ) )
OD
</syntaxhighlight>
=={{header|ALGOL-M}}==
<
INTEGER FUNCTION DIVBY(N, D);
Line 323 ⟶ 404:
END;
END</
=={{header|ALGOL W}}==
<
begin
i_w := 1; % set integers to print in minimum space %
Line 335 ⟶ 416:
else write( i )
end for_i
end.</
=={{header|AntLang}}==
<
s:{a:0eq x mod 3;b:0eq x mod 5;concat apply{1elem x}map{0elem x}hfilter seq[1- max[a;b];a;b]merge seq[str[x];"Fizz";"Buzz"]}map n
echo map s</
=={{header|APEX}}==
<syntaxhighlight lang="apex">
for(integer i=1; i <= 100; i++){
String output = '';
Line 354 ⟶ 435:
}
}
</syntaxhighlight>
=={{header|APL}}==
<
(L,'Fizz' 'Buzz' 'FizzBuzz')[¯1+(L×W=0)+W←(100×~0=W)+W←⊃+/1 2×0=3 5|⊂L←1+⍳100]
</syntaxhighlight>
Slightly different approach that makes use of the Decode function (⊥):
<
A[I]←1+I←(0⍷A)/⍳⍴A←('FIZZBUZZ' 'FIZZ’ 'BUZZ' 0)[2⊥¨×(⊂3 5)|¨1+⍳100]
</syntaxhighlight>
The idea is to first calculate the residues for all numbers 1..100 after
Line 387 ⟶ 468:
Here's a Dyalog-specific solution taking advantage of its anonymous function extension:
<
A slightly different version that works both in Dyalog and GNU APL -- credit to Aniket Bhattacharyea, posted on codeburst.io (https://codeburst.io/fizzbuzz-in-apl-a193d1954b4b):
<
Yet another solution, excessively commented:
Line 397 ⟶ 478:
{{works with|GNU_APL}} (and Dyalog, with [http://course.dyalog.com/autumn2021/Quirks/ ⎕ML ← 2])
<
[1] ⍝⍝ Solve the popular 'fizzbuzz' problem in APL.
[2] ⍝⍝ \param n - highest number to compute (≥0)
Line 436 ⟶ 517:
[37] ⍝⍝ ⎕ ← ,fizzbuzz 15
[38] ⍝ 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz
∇</
I prefer the DRYness of solutions that don't have "FizzBuzz" as a separate case; here's such a solution that works with both Dyalog and GNU. You may want to prepend `⍬⊣` to the whole thing in GNU to keep it from returning the list as the value of the expression, causing the interpreter to print it out a second time.
{{works with|Dyalog APL}}
{{works with|GNU APL}}
<syntaxhighlight lang="apl">⎕io←1
{⎕←∊'Fizz' 'Buzz'⍵/⍨d,⍱/d←0=3 5|⍵}¨⍳100</syntaxhighlight>
Explanation:
<pre>
⎕io←1 Set the index origin to 1; if it were set to 0, the next
step would count from 0 to 99 instead of 1 to 100.
{ }¨⍳100 Do the thing in braces for each integer from 1 through 100.
3 5|⍵ Make a list of the remainders when the current number is
divided by 3 and 5.
d←0= Make it a Boolean vector: true for remainder=0, false
otherwise. Name it d.
d,⍱/ Prepend d to the result of reducing itself with XNOR,
yielding a three-element Boolean vector. The first element
is true if the number is divisible by 3; the second if it's
divisible by 5; and the third only if it's divisible by
neither.
'Fizz' 'Buzz'⍵/⍨ Use the Boolean vector as a mask to select elements from
a new triple consisting of 'Fizz', 'Buzz', and the current
number. Each of the three elements will be included in the
selection only if the corresponding Boolean is true.
∊ Combine the selected elements into one vector/string
⎕← And print it out.</pre>
=={{header|AppleScript}}==
===Procedural===
<
repeat with i from 1 to 100
if i mod 15 = 0 then
Line 453 ⟶ 569:
set outputText to outputText & linefeed
end repeat
outputText</
----
If this were a useful task requiring a degree of efficiency, it would be better to replace the cumulative text concatenations with additions to a fast-to-access list and coerce this list to text in one go at the end. Less critically, the <tt>(i mod … = 0)</tt> tests could be nested to reduce the number of these performed from 261 to 200:
<
script o
property output : {}
Line 484 ⟶ 600:
end fizzBuzz
fizzBuzz(100)</
Another alternative would be simply to fill the list with numbers and then go through it again three times overwriting the relevant slots with the appropriate words:
<
script o
property output : {}
Line 511 ⟶ 627:
end fizzBuzz
fizzBuzz(100)</
With the number of numbers raised from 100 to 10,000, the two scripts inserted here take around 0.051 seconds to execute on my current machine, the original AppleScript above around 0.25 seconds, and the one below (originally described as "functional composition") 3.52 seconds.
Line 517 ⟶ 633:
===Functional===
For simplicity, and more efficient use of the scripter's time:
<
-- fizz :: Int -> Bool
Line 610 ⟶ 726:
end script
end if
end mReturn</
=={{header|Applesoft BASIC}}==
Line 616 ⟶ 732:
=={{header|Arbre}}==
<
for x in [1..100]
if x%5==0 and x%3==0
Line 630 ⟶ 746:
main():
fizzbuzz() -> io</
=={{header|Arc}}==
===Arc 3.1 Base===
<
(prn:if
(multiple n 15) 'FizzBuzz
(multiple n 5) 'Buzz
(multiple n 3) 'Fizz
n))</
<
(prn:check (string (when (multiple n 3) 'Fizz)
(when (multiple n 5) 'Buzz))
~empty n)) ; check created string not empty, else return n</
===Waterhouse Arc===
<
(prn:case (gcd n 15)
1 n
3 'Fizz
5 'Buzz
'FizzBuzz))</
=={{header|ARM Assembly}}==
<syntaxhighlight lang="arm_assembly">
/ * linux GAS */
Line 774 ⟶ 890:
mov r0, r2
mov pc, lr
</syntaxhighlight>
=={{header|Arturo}}==
<
case []
when? [0=x%15] -> print "FizzBuzz"
Line 783 ⟶ 899:
when? [0=x%5] -> print "Buzz"
else -> print x
]</
{{out}}
<pre>1
Line 893 ⟶ 1,009:
=={{header|Asymptote}}==
<
if (number % 15 == 0) {
write("FizzBuzz");
Line 907 ⟶ 1,023:
}
}
}</
=={{header|ATS}}==
<
implement main0() = loop(1, 100) where {
Line 927 ⟶ 1,043:
loop(from+1, to)
end
}</
=={{header|AutoHotkey}}==
{{AutoHotkey case}}
<
{
If (Mod(A_Index, 15) = 0)
Line 944 ⟶ 1,060:
FileDelete, output.txt
FileAppend, %output%, output.txt
Run, cmd /k type output.txt</
A short example with cascading ternary operators and graphical output. Press Esc to close the window.
<
Gui,Show
Loop, 100
Line 952 ⟶ 1,068:
Return
Esc::
ExitApp</
=={{header|AutoIt}}==
===Example1===
Output via MsgBox():
<
If Mod($i, 15) = 0 Then
MsgBox(0, "FizzBuzz", "FizzBuzz")
Line 967 ⟶ 1,083:
MsgBox(0, "FizzBuzz", $i)
EndIf
Next</
===Example2===
Output via console, logfile and/or messagebox:
<
; uncomment how you want to do the output
Line 995 ⟶ 1,111:
EndIf
Next
Out("# Done.")</
=={{header|Avail}}==
<
Print:
if i mod 15 = 0 then ["FizzBuzz"]
Line 1,005 ⟶ 1,121:
else [“i”]
++ "\n";
];</
=={{header|AWK}}==
Line 1,011 ⟶ 1,127:
=={{header|Axe}}==
<
!If I^3??I^5
Disp "FIZZBUZZ",i
Line 1,023 ⟶ 1,139:
.Pause to allow the user to actually read the output
Pause 1000
End</
=={{header|Babel}}==
<
{ { iter 1 + dup
Line 1,047 ⟶ 1,163:
"\n" << }
100 times }</
=={{header|BabyCobol}}==
<syntaxhighlight lang="cobol">
* NB: ANY does not exist in BabyCobol so the elegant
* EVALUATE-based COBOL-style solution is impossible here.
* Note the subtly unbalanced IF/ENDs yet valid END at the end.
IDENTIFICATION DIVISION.
PROGRAM-ID. FIZZBUZZ.
DATA DIVISION.
01 INT PICTURE IS 9(3).
01 REM LIKE INT.
01 TMP LIKE INT.
PROCEDURE DIVISION.
LOOP VARYING INT TO 100
DIVIDE 3 INTO INT GIVING TMP REMAINDER REM
IF REM = 0
THEN DISPLAY "Fizz" WITH NO ADVANCING
DIVIDE 5 INTO INT GIVING TMP REMAINDER REM
IF REM = 0
THEN DISPLAY "Buzz" WITH NO ADVANCING
DIVIDE 15 INTO INT GIVING TMP REMAINDER REM
IF REM = 0
THEN DISPLAY ""
ELSE DISPLAY INT
END.
</syntaxhighlight>
=={{header|BaCon}}==
Line 1,054 ⟶ 1,196:
=={{header|bash}}==
Any bash hacker would do this as a one liner at the shell, so...
<
For the sake of readability...
<
((( n % 15 == 0 )) && echo 'FizzBuzz') ||
((( n % 5 == 0 )) && echo 'Buzz') ||
((( n % 3 == 0 )) && echo 'Fizz') ||
echo $n;
done</
Here's a very concise approach, with only 75 characters total.
Unfortunately it relies on aspects of Bash which are rarely used.
<
Here's the concise approach again, this time separated into multiple lines.
<
for i in {1..100} # Use i to loop from "1" to "100", inclusive.
do ((i % 3)) && # If i is not divisible by 3...
Line 1,074 ⟶ 1,216:
x+=Buzz # ...Otherwise, append (not set) the string "Buzz" to x.
echo ${x:-$i} # Print x unless it is blanked out. Otherwise, print i.
done</
It's a bit silly to optimize such a small & fast program,
but for the sake of algorithm analysis it's worth noting that
Line 1,090 ⟶ 1,232:
=={{header|BASIC}}==
See [[FizzBuzz/Basic]]
=={{header|Basic09}}==
See [[FizzBuzz/Basic]]
Line 1,098 ⟶ 1,243:
FOR /L version:
<
for /L %%i in (1,1,100) do call :tester %%i
goto :eof
Line 1,122 ⟶ 1,267:
:NotFizz
echo %1
</syntaxhighlight>
Loop version:
<
set n=1
Line 1,154 ⟶ 1,299:
:NotFizz
echo %1</
FOR /L with a block instead of very-high-overhead subroutine call:
<
for /l %%i in (1,1,100) do (
set /a m5=%%i %% 5
Line 1,167 ⟶ 1,312:
if "!s!"=="" set s=%%i
echo !s!
)</
=={{header|BBC BASIC}}==
Line 1,175 ⟶ 1,320:
This solution never uses <tt>else</tt>, because bc has no <tt>else</tt> keyword (but some implementations add <tt>else</tt> as an extension).
<
w = 0
if (i % 3 == 0) { "Fizz"; w = 1; }
Line 1,183 ⟶ 1,328:
"
}
quit</
=={{header|BCPL}}==
<
LET start() BE $(
Line 1,204 ⟶ 1,349:
$)
$)
</syntaxhighlight>
=={{header|beeswax}}==
Line 1,212 ⟶ 1,357:
“Ordinary” FizzBuzz solution:
<
>@F5~%"d@F{ > @F q
_1>F3~%'d`Fizz`@F5~%'d >`Buzz`@FNp
;bL@~.~4~.5~5@ P<</
Example without double mod 5 check, using a flag instead, to check if Fizz already got printed (in this case the number n must not be printed if mod 5 is > 0):
<
> q >Ag'd@{?p
_>"1F3~%'d`Fizz`f>@F5~%'d`Buzz`@p
b P~;"-~@~.+0~P9@N?<</
=={{header|Befunge}}==
Line 1,229 ⟶ 1,374:
=={{header|blz}}==
<
out = ""
if i % 3 == 0
Line 1,241 ⟶ 1,386:
end
print(out)
end</
=={{header|Boo}}==
<
for i in range(1, size):
if i%15 == 0:
Line 1,255 ⟶ 1,400:
print i
fizzbuzz(101)</
=={{header|BQN}}==
<
Using the Catch modifier for flow control
<syntaxhighlight lang="bqn">((∾´"fizz"‿"buzz"/˜0=3‿5|⊢)⎊⊢)¨1+↕100</syntaxhighlight>
Using the Choose Combonator with a rank 2 array
<syntaxhighlight lang="bqn">(3‿5 (0=|)◶[⊢‿"fizz","buzz"‿"fizzbuzz"] ⊢)¨ 1+↕100</syntaxhighlight>
=={{header|Bracmat}}==
<
Same code, pretty printed:
<
& whl
' ( 1+!i:<101:?i
Line 1,274 ⟶ 1,425:
| !i
)
)</
=={{header|Brainf***}}==
Line 1,280 ⟶ 1,431:
=={{header|Brat}}==
<
true? n % 15 == 0
{ p "FizzBuzz" }
Line 1,290 ⟶ 1,441:
}
}
}</
=={{header|BrightScript (for Roku)}}==
<
fz = i MOD 3 = 0
bz = i MOD 5 = 0
Line 1,305 ⟶ 1,456:
END IF
? str
END FOR</
=={{header|Bruijn}}==
<syntaxhighlight lang="bruijn">
:import std/Combinator .
:import std/String .
:import std/Number .
main [y [[0 =? (+101) case-end case-rec]] (+1)]
case-rec str ++ "\n" ++ (1 ++0)
str fizzbuzz "FizzBuzz" (fizz "Fizz" (buzz "Buzz" (number→string 0)))
fizz =?(0 % (+3))
buzz =?(0 % (+5))
fizzbuzz fizz buzz fizz
case-end empty
</syntaxhighlight>
=={{header|C}}==
For 2 prime numbers and based on a similar minimal [[#JavaScript|JavaScript]] solution with low signal-to-noise, the C code is:
<
while ( i++ < 100 )
!sprintf( B, "%s%s", i%3 ? "":"Fizz", i%5 ? "":"Buzz" )
? sprintf( B, "%d", i ):0, printf( ", %s", B );</
With 4 prime numbers:
<
while ( i++ < 100 )
!sprintf( B, "%s%s%s%s",
i%3 ? "":"Fiz", i%5 ? "":"Buz", i%7 ? "":"Goz", i%11 ? "":"Kaz" )
? sprintf( B, "%d", i ):0, printf( ", %s", B );</
<
One line version, with pretty printing
<
int main() {
for (int i=1; i<=105; i++) if (i%3 && i%5) printf("%3d ", i); else printf("%s%s%s", i%3?"":"Fizz", i%5?"":"Buzz", i%15?" ":"\n");
}
</syntaxhighlight>
This actually works (the array init part, saves 6 bytes of static data, whee):<
int main ()
Line 1,338 ⟶ 1,504:
printf(s[!(i % 3) + 2 * !(i % 5)], i);
return 0;
}</
<
int main (void)
Line 1,359 ⟶ 1,525:
}
return 0;
}</
Implicit int main and return 0 (C99+):
<
main() {
Line 1,376 ⟶ 1,542:
i++;
}
}</
obfuscated:
<
#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;}</
With numbers theory: <
int main(void)
Line 1,393 ⟶ 1,559:
}
}
</syntaxhighlight>
Without conditionals, anything in the loop body gcc compiles with branching, duplicate tests or duplicate strings. Depends on ASCII and two's complement arithmetic:
<
int main()
{
Line 1,407 ⟶ 1,573:
}
}
</syntaxhighlight>
=={{header|C sharp|C#}}==
<
{
public void FizzBuzzGo()
Line 1,443 ⟶ 1,609:
}
}
}</
<
{
static void Main()
Line 1,462 ⟶ 1,628:
}
}
}</
<
using System.Linq;
Line 1,480 ⟶ 1,646:
}
}
}</
<
using System.Globalization;
using System.Linq;
Line 1,504 ⟶ 1,670:
}
}
}</
<
namespace FizzBuzz
{
Line 1,534 ⟶ 1,700:
}
}
}</
<
using System.Globalization;
Line 1,565 ⟶ 1,731:
}
}
}</
<
using System.Linq;
Line 1,579 ⟶ 1,745:
}
}
}</
===With C#8 switch expressions===
<
{
public static string FizzBuzzIt(int n) =>
Line 1,601 ⟶ 1,767:
}
}
}</
===TDD using delegates===
<
using System.Collections;
using System.Collections.Generic;
Line 1,687 ⟶ 1,853:
}
}
}</
===Good old C ways===
<
int max = 100;
for(int i=0;
Line 1,697 ⟶ 1,863:
Console.WriteLine("{0}{1}{2}", i%3==0 ? "Fizz" : "", i%5==0 ? "Buzz" : "", i%3!=0 && i%5!=0 ? i.ToString() : "")
){}
</syntaxhighlight>
=={{header|C++}}==
===minimal conditions===
<
#include <chrono>
Line 1,740 ⟶ 1,906:
return 0;
}
</syntaxhighlight>
===with modulo===
<
using namespace std;
Line 1,759 ⟶ 1,925:
}
return 0;
}</
===without modulo 15===
<
using namespace std;
Line 1,779 ⟶ 1,945:
}
return 0;
}</
===without modulo===
Modulo can be expensive on some architectures.
<
int main()
Line 1,798 ⟶ 1,964:
return 0;
}
</syntaxhighlight>
===using std::transform===
{{works with|C++11}}
<
#include <algorithm>
#include <vector>
Line 1,825 ⟶ 1,991:
return 0;
}</
===metaprogramming===
Version computing FizzBuzz at compile time with metaprogramming:
<
template <int n, int m3, int m5>
Line 1,875 ⟶ 2,041:
fb_run<100> fb;
return 0;
}</
===hardcore templates===
Compile with -ftemplate-depth-9000 -std=c++0x:
<
#include <string>
#include <cstdlib>
Line 2,041 ⟶ 2,207:
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).
Line 2,048 ⟶ 2,214:
=={{header|Cduce}}==
<
let format (n : Int) : Latin1 =
Line 2,065 ⟶ 2,231:
let fizbuzz (size : Int) : _ = fizz (1, size);;
let _ = fizbuzz(100);;</
=={{header|Ceylon}}==
<
=={{header|Chapel}}==
<
for i in 1..n do
if i % 15 == 0 then
Line 2,083 ⟶ 2,249:
}
fizzbuzz(100);</
=={{header|Chef}}==
See [[FizzBuzz/EsoLang]]
=={{header|Cherrycake}}==
<syntaxhighlight lang="cherrycake">
# Route with custom number of iterations
cached get ~/:n {
# Get the Number of Iterations from the URL Params
int n = req.params.n || 100
# Loop through each iteration
for (i in range(n)) {
if (i % 2 == 0 && i % 3 == 0) { res.write("FizzBuzz\n") continue }
if (i % 2 == 0) { res.write("Fizz\n"); continue; }
if (i % 3 == 0) { res.write("Buzz\n"); continue; }
res.write(i + "\n");
}
# Close the connection
res.end();
}
</syntaxhighlight>
=={{header|Clay}}==
<
for(i in range(1,100)) {
if(i % 3 == 0 and i % 5 == 0) println("fizzbuzz");
Line 2,096 ⟶ 2,286:
else print(i);
}
}</
=={{header|Clipper}}==
Also compiles with Harbour (Harbour 3.2.0dev (r1405201749))
<
LOCAL n
Line 2,112 ⟶ 2,302:
RETURN
</syntaxhighlight>
The advantage of this approach is that it is trivial to add another factor:
<pre>AEval( {{3,"Fizz"},{5,"Buzz"},{9,"Jazz"}}, {|x| cFB += Iif((n % x[1])==0, x[2], "")})</pre>
=={{header|CLIPS}}==
<
(count-to 100)
)
Line 2,142 ⟶ 2,332:
(priint depth, unsigned int i> struct NUM_DIGITS_CORE : NUM_DIGITS_COREntout t crlf)
)
)</
=={{header|Clojure}}==
<
(doseq [x (range 1 101)] (println x (str (when (zero? (mod x 3)) "fizz") (when (zero? (mod x 5)) "buzz"))))
</syntaxhighlight>
<
(defn fizzbuzz [start finish]
(map (fn [n]
Line 2,159 ⟶ 2,349:
(range start finish)))
(fizzbuzz 1 100)
</syntaxhighlight>
<
(zero? (mod x 5)) "Buzz"
(zero? (mod x 3)) "Fizz"
:else x))
(range 1 101))</
<
<
#(cond (zero? (mod % 15)) "FizzBuzz"
(zero? (mod % 5)) "Buzz"
(zero? (mod % 3)) "Fizz"
:else %)
(iterate inc 1)))</
<
([] (fizz-buzz (range 1 101)))
([lst]
Line 2,186 ⟶ 2,376:
(buzz? n) b
:else n))
lst)] items))))</
<
(if-let [fb (seq (concat (when (zero? (mod n 3)) "Fizz")
(when (zero? (mod n 5)) "Buzz")))]
(apply str fb)
n))
(range 1 101))</
<
(range)
(cycle [ "" "" "Fizz" ])
(cycle [ "" "" "" "" "Buzz" ])))</
<
<
(take 20 (map #(if (or %1 %2) (str %1 %2) %3) fizz buzz nums)))</
<
(map #(if (pos? (compare %1 %2)) %1 %2)
(map str (drop 1 (range)))
(map str (cycle ["" "" "Fizz"]) (cycle ["" "" "" "" "Buzz"]))))
</syntaxhighlight>
<
;;Using clojure maps
(defn fizzbuzz
Line 2,225 ⟶ 2,415:
[max]
(map fizzbuzz (range 1 (inc max))))
</syntaxhighlight>
<
(take 100
(map #(str %1 %2 (if-not (or %1 %2) %3))
Line 2,233 ⟶ 2,423:
(rest (range))
))
</syntaxhighlight>
<
(take 100
(
Line 2,254 ⟶ 2,444:
) ;;endfn apply
) ;;endtake
</syntaxhighlight>
<
(take 100
(map-indexed
Line 2,263 ⟶ 2,453:
)
)
</syntaxhighlight>
<
(take 100
(->>
Line 2,272 ⟶ 2,462:
)
)
</syntaxhighlight>
<
(take 100
(map-indexed
Line 2,281 ⟶ 2,471:
)
)
</syntaxhighlight>
=={{header|CLU}}==
<
po: stream := stream$primary_output()
Line 2,294 ⟶ 2,484:
stream$putl(po, out)
end
end start_up</
=={{header|CMake}}==
<
math(EXPR off3 "${i} % 3")
math(EXPR off5 "${i} % 5")
Line 2,309 ⟶ 2,499:
message(${i})
endif()
endforeach(i)</
=={{header|COBOL}}==
Line 2,315 ⟶ 2,505:
===Canonical version===
{{works with|OpenCOBOL}}<!-- http://www.opencobol.org/ -->
<
* cobc -x -g FIZZBUZZ.COB
*
Line 2,350 ⟶ 2,540:
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}}
<
Program-id. fizz-buzz.
Line 2,370 ⟶ 2,560:
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.
Line 2,401 ⟶ 2,591:
STOP RUN
.
</syntaxhighlight>
===Chase the Fizz===
{{works with|OpenCOBOL}}
A solution that simply evaluates and adds.
<
identification division.
program-id. fizzbuzz.
Line 2,435 ⟶ 2,625:
.
end program fizzbuzz.
</syntaxhighlight>
=={{header|Coco}}==
<
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</
<
console.log(['Fizz' unless i % 3] + ['Buzz' unless i % 5] or String(i))</
=={{header|Coconut}}==
<
case (n % 3, n % 5):
match (0, 0): return "FizzBuzz"
Line 2,455 ⟶ 2,645:
match (_, 0): return "Buzz"
else: return n |> str
range(1,101)|> map$(fizzbuzz)|> x -> '\n'.join(x)|> print</
=={{header|CoffeeScript}}==
<
if i % 15 is 0
console.log "FizzBuzz"
Line 2,466 ⟶ 2,656:
console.log "Buzz"
else
console.log i</
<
console.log \
if i % 15 is 0
Line 2,476 ⟶ 2,666:
"Buzz"
else
i</
<
console.log(['Fizz' if i % 3 is 0] + ['Buzz' if i % 5 is 0] or i)</
=={{header|ColdFusion}}==
<
<Cfif i mod 15 eq 0>FizzBuzz
<Cfelseif i mod 5 eq 0>Fizz
Line 2,487 ⟶ 2,677:
<Cfelse><Cfoutput>#i# </Cfoutput>
</Cfif>
</Cfloop></
cfscript version
<
result = "";
for(i=1;i<=100;i++){
Line 2,495 ⟶ 2,685:
}
WriteOutput(result);
</cfscript></
=={{header|Comal}}==
<
0020 IF i# MOD 15=0 THEN
0030 PRINT "FizzBuzz"
Line 2,509 ⟶ 2,699:
0100 ENDIF
0110 ENDFOR i#
0120 END</
=={{header|Comefrom0x10}}==
<
mod_three = 3
mod_five = 5
Line 2,536 ⟶ 2,726:
mod_five = mod_five + 5
comefrom fizzbuzz if n is 100</
=={{header|Commodore BASIC}}==
See [[FizzBuzz/Basic]]
=={{header|Common Lisp}}==
Solution 1:
<
(loop for x from 1 to 100 do
(princ (cond ((zerop (mod x 15)) "FizzBuzz")
Line 2,546 ⟶ 2,739:
((zerop (mod x 5)) "Buzz")
(t x)))
(terpri)))</
Solution 2:
<
(loop for x from 1 to 100 do
(format t "~&~{~A~}"
(or (append (when (zerop (mod x 3)) '("Fizz"))
(when (zerop (mod x 5)) '("Buzz")))
(list x)))))</
Solution 3:
<
(loop for n from 1 to 100
do (format t "~&~[~[FizzBuzz~:;Fizz~]~*~:;~[Buzz~*~:;~D~]~]~%"
(mod n 3) (mod n 5) n)))</
Solution 4:
<
as fizz = (zerop (mod n 3))
as buzz = (zerop (mod n 5))
Line 2,567 ⟶ 2,760:
(format t
"~&~:[~;Fizz~]~:[~;Buzz~]~:[~;~D~]~%"
fizz buzz numb n))</
Solution 5:
<
(loop as n from 1 to 100
as f = (zerop (mod n 3))
Line 2,576 ⟶ 2,769:
if f collect 'fizz
if b collect 'buzz
if (not (or f b)) collect n))</
Solution 6:
<
(loop as n from 1 to 100
as f = (zerop (mod n 3))
as b = (zerop (mod n 5))
collect (list f b (not (or f b)) n)))</
Solution 7:
<
(mapcar
#'(lambda (a b) (if (equal 0 (mod x a)) b x))
Line 2,600 ⟶ 2,793:
(print (format nil "~{~a~}" (filter-core (core a))))))
(fizzbuzz 100)</
Solution 8:
<syntaxhighlight lang="lisp">(defun range (min max)
(loop
:for x :from min :to max
:collect x))
(defun fizzbuzz ()
(map 'nil #'(lambda (n)
(princ
(cond
((zerop (mod n 15)) "FizzBuzz!")
((zerop (mod n 5)) "Buzz!")
((zerop (mod n 3)) "Fizz!")
(t n))
(terpri)))
(range 1 100)))</syntaxhighlight>
First 16 lines of output:
<pre>
Line 2,624 ⟶ 2,835:
I use [https://franz.com/downloads/clp/survey Allegro CL 10.1]
<
;; Project : FizzBuzz
Line 2,645 ⟶ 2,856:
(= (rem n multiple) 0))
(fizzbuzz 1)
</syntaxhighlight>
Output:
<pre>
Line 2,669 ⟶ 2,880:
Buzz
</pre>
=={{header|Coq}}==
<
Require Import Coq.Lists.List.
(* https://coq.inria.fr/library/Coq.Lists.List.html *)
Line 2,689 ⟶ 2,899:
(** Definition of [string_of_nat] to convert natural numbers to strings. *)
Definition ascii_of_digit (n : nat) : ascii :=
ascii_of_nat (n + 48).
Definition is_digit (n : nat) : bool :=
andb (0 <=? n) (n <=? 9).
Fixpoint rec_string_of_nat (counter : nat) (n : nat) (acc : string) : string :=
match counter with
| 0 => EmptyString
| S c =>
if (is_digit n)
then String (ascii_of_digit n) acc
Line 2,705 ⟶ 2,915:
(** The counter is only used to ensure termination. *)
Definition string_of_nat (n : nat) : string :=
rec_string_of_nat n n EmptyString.
Line 2,711 ⟶ 2,921:
(** The FizzBuzz problem. *)
Definition fizz : string :=
"Fizz"
Definition buzz : string :=
"Buzz"
Definition new_line : string :=
String (ascii_of_nat 10) EmptyString.
Definition is_divisible_by (n : nat) (k : nat) : bool :=
(n mod k) =? 0.
Definition
if (is_divisible_by n 15) then fizz ++ buzz
else if (is_divisible_by n 3) then fizz
Line 2,729 ⟶ 2,939:
else (string_of_nat n).
Definition
seq
Definition
map
Definition fizz_buzz : string :=
concat new_line (
(** This shows the string. *)
Eval compute in fizz_buzz.
</syntaxhighlight>
Output
<pre>
= "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"%string
: string
</pre>
=={{header|Cowgol}}==
Line 2,747 ⟶ 3,062:
===Straightforward version===
<
var i: uint8 := 1;
Line 2,762 ⟶ 3,077:
print_nl();
i := i + 1;
end loop;</
===No division===
Line 2,781 ⟶ 3,096:
98-byte executable.)
<
var i: uint8 := 100;
Line 2,823 ⟶ 3,138:
i := i - 1;
end loop;
</syntaxhighlight>
=={{header|Craft Basic}}==
See [[FizzBuzz/Basic]]
=={{header|Crystal}}==
<
p fizz_buzz(v)
end
Line 2,837 ⟶ 3,154:
word += value.to_s if word.empty?
word
end</
A more natural solution with the string building:
<
case
when n % 15 == 0
Line 2,852 ⟶ 3,169:
puts n
end
end</
=={{header|CSS}}==
Line 2,982 ⟶ 3,299:
=={{header|Cubescript}}==
<syntaxhighlight lang="text">alias fizzbuzz [
loop i 100 [
push i (+ $i 1) [
Line 2,996 ⟶ 3,313:
]
]
]</
=={{header|D}}==
<
/// With if-else.
Line 3,051 ⟶ 3,368:
writeln;
100.fizzBuzzSwitch2;
}</
Alternate version calculating values at compile time:
<
void main()
Line 3,069 ⟶ 3,386:
r.each!writeln;
}</
=={{header|Dart}}==
<
main() {
for (int i = 1; i <= 100; i++) {
Line 3,083 ⟶ 3,400:
}
}
</syntaxhighlight>
=={{header|dc}}==
{{trans|bc}}
<
[[Buzz]P 1 sw]sB
[li p sz]sN
Line 3,102 ⟶ 3,419:
]sL
1 si [i = 1]sz
0 0 =L [enter Loop]sz</
The bc translation written in dc style.
<syntaxhighlight lang="dc">
# dc is stack based, so we use the stack instead of a variable for our
# current number.
Line 3,122 ⟶ 3,439:
1+d # Number += 1 and put extra copy on stack
100!<L # Continue Loop if 100 >= Number (destroys copy)
]dsLx # Enter Loop</
=={{header|Delphi}}==
<
{$APPTYPE CONSOLE}
Line 3,145 ⟶ 3,462:
Writeln(i);
end;
end.</
=={{header|DeviousYarn}}==
<
? { divisible(x 3)
p:'Fizz' }
Line 3,156 ⟶ 3,473:
p:x }
o
}</
=={{header|Draco}}==
<
byte i;
for i from 1 upto 100 do
Line 3,168 ⟶ 3,485:
fi
od
corp</
=={{header|DUP}}==
Line 3,175 ⟶ 3,492:
Output to STDOUT via single character output.
<
0[$100<][1+c;!]# {loop from 1 to 100}</
Output to STDOUT, using stored strings and a separately defined string output operator:
<
[$$3/%$[][0$"Fizz"P]?\5/%$[][0$"Buzz"P]?*[$.][]?10,]c: {define function c: mod 3, mod 5 tests, print according output}
0[$100<][1+c;!]# {loop from 1 to 100}</
=={{header|DWScript}}==
<
for i := 1 to 100 do begin
Line 3,194 ⟶ 3,511:
PrintLn('Buzz')
else PrintLn(i);
end;</
=={{header|Dyalect}}==
<
while n < 20 {
Line 3,212 ⟶ 3,529:
n = n + 1
}</
{{out}}
Line 3,237 ⟶ 3,554:
=={{header|Déjà Vu}}==
<
if = 0 % i 15:
"FizzBuzz"
Line 3,246 ⟶ 3,563:
else:
i
!print</
=={{header|E}}==
<
println(switch ([i % 3, i % 5]) {
match [==0, ==0] { "FizzBuzz" }
Line 3,256 ⟶ 3,573:
match _ { i }
})
}</
=={{header|EasyLang}}==
<syntaxhighlight lang="text">for i = 1 to 100
if i mod 15 = 0
print "FizzBuzz"
Line 3,269 ⟶ 3,586:
print i
.
.</
=={{header|ECL}}==
<
STRING s;
END;
Line 3,288 ⟶ 3,605:
d := DATASET(100,MakeDataRec(COUNTER));
OUTPUT(d);</
=={{header|Ecstasy}}==
<syntaxhighlight lang="java">
module FizzBuzz {
void run() {
@Inject Console console;
for (Int x : 1..100) {
console.print(switch (x % 3, x % 5) {
case (0, 0): "FizzBuzz";
case (0, _): "Fizz";
case (_, 0): "Buzz";
case (_, _): x.toString();
});
}
}
}
</syntaxhighlight>
=={{header|Ed}}==
<syntaxhighlight lang="bash">H
a
100
.
# iota.ed
g/[^0-9]{1,}/s///g
,p
# decimal -> unary
g/^0+([0-9])/s//\1/
g/^9([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiiiiii/
g/^8([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiiiii/
g/^7([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiiii/
g/^6([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiii/
g/^5([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiiii/
g/^4([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiii/
g/^3([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iii/
g/^2([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2ii/
g/^1([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2i/
g/^0([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2/
g/^9([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiiiiii/
g/^8([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiiiii/
g/^7([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiiii/
g/^6([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiii/
g/^5([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiiii/
g/^4([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiii/
g/^3([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iii/
g/^2([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2ii/
g/^1([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2i/
g/^0([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2/
g/^9([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiiiiii/
g/^8([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiiiii/
g/^7([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiiii/
g/^6([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiii/
g/^5([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiiii/
g/^4([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiii/
g/^3([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iii/
g/^2([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2ii/
g/^1([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2i/
g/^0([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2/
g/^9([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiiiiii/
g/^8([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiiiii/
g/^7([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiiii/
g/^6([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiii/
g/^5([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiiii/
g/^4([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiii/
g/^3([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iii/
g/^2([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2ii/
g/^1([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2i/
g/^0([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2/
g/^9([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiiiiii/
g/^8([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiiiii/
g/^7([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiiii/
g/^6([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiiiii/
g/^5([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiiii/
g/^4([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iiii/
g/^3([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2iii/
g/^2([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2ii/
g/^1([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2i/
g/^0([0-9]*)(i*)/s//\1\2\2\2\2\2\2\2\2\2\2/
# iota logic
s/\B/\
/g
a
.
y
d
g/i/x\
s/.*/&i/\
-1d\
y
# fizzbuzz
g/^(i{15})+$/s//FizzBuzz/
g/^(i{5})+$/s//Buzz/
g/^(i{3})+$/s//Fizz/
# unary -> decimal (for 0-10000 range)
g/i{9000}(i{0,999})/s//9\1/
g/i{8000}(i{0,999})/s//8\1/
g/i{7000}(i{0,999})/s//7\1/
g/i{6000}(i{0,999})/s//6\1/
g/i{5000}(i{0,999})/s//5\1/
g/i{4000}(i{0,999})/s//4\1/
g/i{3000}(i{0,999})/s//3\1/
g/i{2000}(i{0,999})/s//2\1/
g/i{1000}(i{0,999})/s//1\1/
v/^[0-9]i*$/s/.*/0&/
g/i{900}(i{0,99})/s//9\1/
g/i{800}(i{0,99})/s//8\1/
g/i{700}(i{0,99})/s//7\1/
g/i{600}(i{0,99})/s//6\1/
g/i{500}(i{0,99})/s//5\1/
g/i{400}(i{0,99})/s//4\1/
g/i{300}(i{0,99})/s//3\1/
g/i{200}(i{0,99})/s//2\1/
g/i{100}(i{0,99})/s//1\1/
v/^[0-9]{2}i*$/s/^([0-9])(i*)$/\10\2/
g/i{90}(i{0,9})/s//9\1/
g/i{80}(i{0,9})/s//8\1/
g/i{70}(i{0,9})/s//7\1/
g/i{60}(i{0,9})/s//6\1/
g/i{50}(i{0,9})/s//5\1/
g/i{40}(i{0,9})/s//4\1/
g/i{30}(i{0,9})/s//3\1/
g/i{20}(i{0,9})/s//2\1/
g/i{10}(i{0,9})/s//1\1/
v/^[0-9]{3}i*$/s/^([0-9]{2})(i*)$/\10\2/
g/i{9}/s//9/
g/i{8}/s//8/
g/i{7}/s//7/
g/i{6}/s//6/
g/i{5}/s//5/
g/i{4}/s//4/
g/i{3}/s//3/
g/i{2}/s//2/
g/i{1}/s//1/
v/^[0-9]{4}i*$/s/^([0-9]{3})(i*)$/\10\2/
g/^0+([0-9])/s//\1/
g/0F1zz/s//Fizz/
g/0Buzz/s//Buzz/
,p
Q
</syntaxhighlight>
=={{header|Eero}}==
<
int main()
Line 3,304 ⟶ 3,762:
Log( '(%d) %@', i, s )
return 0</
=={{header|Egel}}==
<syntaxhighlight lang="egel">
import "prelude.eg"
import "io.ego"
Line 3,327 ⟶ 3,785:
def main = fizzbuzz 1
</syntaxhighlight>
=={{header|Eiffel}}==
<syntaxhighlight lang="eiffel">
class
APPLICATION
Line 3,365 ⟶ 3,823:
end
</syntaxhighlight>
=={{header|Ela}}==
<
prt x | x % 15 == 0 = "FizzBuzz"
Line 3,375 ⟶ 3,833:
| else = x
[1..100] |> map prt</
=={{header|Elixir}}==
===Standard approaches===
used case
<
IO.puts(case { rem(x,3) == 0, rem(x,5) == 0 } do
{ true, true } -> "FizzBuzz"
Line 3,387 ⟶ 3,845:
{ false, false } -> x
end)
end</
Alternate approach using pipes and cond:
<
1..100 |> Enum.map(fn i ->
cond do
Line 3,399 ⟶ 3,857:
true -> i
end
end) |> Enum.each(fn i -> IO.puts i end)</
used Stream.cycle version:
<
def fizzbuzz(limit \\ 100) do
fizz = Stream.cycle(["", "", "Fizz"])
Line 3,415 ⟶ 3,873:
end
RC.fizzbuzz</
Yet another approach:
<
def fizzbuzz(n) when rem(n, 15) == 0, do: "FizzBuzz"
def fizzbuzz(n) when rem(n, 5) == 0, do: "Buzz"
Line 3,425 ⟶ 3,883:
end
Enum.each(1..100, &IO.puts FizzBuzz.fizzbuzz &1)</
used anonymous function
<
(n) when rem(n,5)==0 -> "Fizz"
(n) when rem(n,3)==0 -> "Buzz"
Line 3,434 ⟶ 3,892:
end
for n <- 1..100, do: IO.puts f.(n)</
Enum.at version: Returns nil if index is out of bounds.
<
str = "#{Enum.at([:Fizz], rem(i,3))}#{Enum.at([:Buzz], rem(i,5))}"
IO.puts if str=="", do: i, else: str
end)</
===A macro too far===
The Stream.cycle version above, but as an overpowered FizzBuzz DSL.
<
# Hand-rolls a bunch of AST before injecting the resulting FizzBuzz code.
defmacrop automate_fizz(fizzers, n) do
Line 3,534 ⟶ 3,992:
end
BadFizz.fizz(100) # => Prints to stdout</
=={{header|Elm}}==
A bit too simple:
<
import List exposing (map)
Line 3,552 ⟶ 4,010:
"Buzz"
else
String.fromInt num</
A bit too clever:
<
import List exposing (map)
import String exposing (join, fromInt)
Line 3,572 ⟶ 4,030:
fromInt num
else
fizz ++ buzz</
=={{header|Emacs Lisp}}==
<
(cond ((and (zerop (% n 5)) (zerop (% n 3))) "FizzBuzz")
((zerop (% n 3)) "Fizz")
Line 3,583 ⟶ 4,041:
;; loop & print from 0 to 100
(dotimes (i 101)
(message "%s" (fizzbuzz i)))</
=={{header|EMal}}==
<syntaxhighlight lang="emal">
logic isFizz, isBuzz
for int count = 1; count <= 100; ++count
isFizz = count % 3 == 0
isBuzz = count % 5 == 0
if isFizz and isBuzz do writeLine("Fizz Buzz")
else if isFizz do writeLine("Fizz")
else if isBuzz do writeLine("Buzz")
else do writeLine(count)
end
end
</syntaxhighlight>
=={{header|Emojicode}}==
===Simple 1===
<
🔂 i 🆕⏩ 1 101 1 ❗ 🍇
↪️ i 🚮 15 🙌 0 🍇
Line 3,601 ⟶ 4,073:
🍉
🍉
🍉</
===Simple 2===
<
🔂 i 🆕⏩ 1 101 1 ❗ 🍇
🔤🔤 ➡️ 🖍🆕 msg
Line 3,618 ⟶ 4,090:
🍉
🍉
🍉</
=={{header|Enguage}}==
<syntaxhighlight lang="Enguage">FizzBuzz</syntaxhighlight>
This source code is supposed to look like plain old English but is, in fact, executable. When used in an Android app, it gives the user direct access to computational abilities of your phone.
It is taken from [https://bitbucket.org/martinwheatman/enguage/src/develop/etc/dict/f/fizzbuzz.entry the dictionary entry for fizzbuzz]
This shows the interpretation of two utterances, the latter of which are called recursively. Enguage is not very efficient, but that's not its goal!
NB. Any line beginning with a '#' is a comment, like Unix shells, but any comment following the ']' character are unit tests exercising this code.
<pre>
On "what is the fizzbuzz of N":
is N divisible by 5 and 3;
if so, reply "fizzbuzz";
is N divisible by 5;
if so, reply "buzz";
is N divisible by 3;
if so, reply "fizz";
reply "N".
On "do fizzbuzz between N and LIMIT":
what is the fizzbuzz of N;
remember this;
set next to the evaluation of N + 1;
NEXT is equal to LIMIT;
if so, what is the fizzbuzz of LIMIT;
if not, do fizzbuzz between NEXT and LIMIT.
#] what is the fizzbuzz of 1: 1.
#] what is the fizzbuzz of 12: fizz.
#] what is the fizzbuzz of 25: buzz.
#] what is the fizzbuzz of 75: fizzbuzz.
#] set limit to 5.
#] do fizzbuzz between 1 and LIMIT.
</pre>
On downloading this repo, if git and make are installed, this unit test can be run with:
<pre>
$ git clone https://github.com/martinwheatman/enguage.git
$ cd enguage
$ make jar
$ export PATH=$PATH:./sbin
$ java -jar lib/enguage.jar -T fizzbuzz
</pre>
Output:
<pre>
TEST: fizzbuzz
==============
user> what is the fizzbuzz of 1.
enguage> 1.
user> what is the fizzbuzz of 12.
enguage> fizz.
user> what is the fizzbuzz of 25.
enguage> buzz.
user> what is the fizzbuzz of 75.
enguage> fizzbuzz.
user> set limit to 5.
enguage> ok , limit is set to 5.
user> do fizzbuzz between 1 and LIMIT.
enguage> 1 . 2 . fizz . 4 . buzz.
1 test group(s) found
+++ PASSED 6 tests in 442ms +++
</pre>
=={{header|Erlang}}==
<
fizzbuzz() ->
F = fun(N) when N rem 15 == 0 -> "FizzBuzz";
Line 3,628 ⟶ 4,176:
(N) -> integer_to_list(N)
end,
lists:flatten([[F(N)] ++ ["\n"] || N <- lists:seq(1,100)]).</
=={{header|ERRE}}==
<syntaxhighlight lang="erre">
PROGRAM FIZZ_BUZZ
!
Line 3,649 ⟶ 4,197:
END FOR
END PROGRAM
</syntaxhighlight>
=={{header|Euler}}==
The original Euler implementations did not allow "long" strings, hence the use of a list here to print FizzBuzz.
'''begin''' '''new''' i; '''label''' iLoop;
i <- 0;
iLoop: '''if''' [ i <- i + 1 ] <= 100 '''then''' '''begin'''
'''out''' '''if''' i '''mod''' 15 = 0 '''then''' ( "Fizz", "Buzz" )
'''else''' '''if''' i '''mod''' 5 = 0 '''then''' "Buzz"
'''else''' '''if''' i '''mod''' 3 = 0 '''then''' "Fizz"
'''else''' i;
'''goto''' iLoop
'''end''' '''else''' 0
'''end''' $
=={{header|Euphoria}}==
{{works with|Euphoria|4.0.0}}
This is based on the [[VBScript]] example.
<
function fb( atom n )
Line 3,686 ⟶ 4,247:
end for
puts( 1, "\n" )</
=={{header|F Sharp|F#}}==
<
match n%3 = 0, n%5 = 0 with
| true, false -> "fizz"
Line 3,697 ⟶ 4,258:
let printFizzbuzz() =
[1..100] |> List.iter (fizzbuzz >> printfn "%s")</
<
|> List.map (fun x ->
match x with
Line 3,705 ⟶ 4,266:
| _ when x % 3 = 0 -> "fizz"
| _ -> x.ToString())
|> List.iter (fun x -> printfn "%s" x) </
Another example using (unnecessary) partial active pattern :D
<
if Seq.exists ((%) number >> (<>) 0) divisors
then None
Line 3,719 ⟶ 4,280:
{ 1 .. 100 }
|> Seq.iter (fizzbuzz >> printfn "%s")</
=={{header|Factor}}==
<
IN: fizzbuzz
: fizz ( n -- str ) 3 divisor? "Fizz" "" ? ;
Line 3,728 ⟶ 4,289:
: fizzbuzz ( n -- str ) dup [ fizz ] [ buzz ] bi append [ number>string ] [ nip ] if-empty ;
: main ( -- ) 100 [1,b] [ fizzbuzz print ] each ;
MAIN: main</
More flexible variant without divisibility tests.
<
USING: kernel sequences arrays generalizations fry math math.parser prettyprint ;
IN: fizzbuzz
Line 3,751 ⟶ 4,312:
MAIN: FizzBuzzQuxx-100
</syntaxhighlight>
Another approach is leverage Factor's [https://docs.factorcode.org/content/article-predicates.html predicate] and [https://docs.factorcode.org/content/article-intersections.html intersection] classes.
<syntaxhighlight lang="factor">
USING: io kernel math math.functions math.parser ranges
sequences ;
IN: rosetta-code.fizz-buzz
PREDICATE: fizz < integer 3 divisor? ;
PREDICATE: buzz < integer 5 divisor? ;
INTERSECTION: fizzbuzz fizz buzz ;
GENERIC: fizzbuzz>string ( n -- str )
M: fizz fizzbuzz>string
drop "Fizz" ;
M: buzz fizzbuzz>string
drop "Buzz" ;
M: fizzbuzz fizzbuzz>string
drop "FizzBuzz" ;
M: integer fizzbuzz>string
number>string ;
MAIN: [ 1 100 [a..b] [ fizzbuzz>string print ] each ]
</syntaxhighlight>
=={{header|Falcon}}==
<
switch i % 15
case 0 : > "FizzBuzz"
Line 3,761 ⟶ 4,350:
default : > i
end
end</
=={{header|FALSE}}==
Line 3,767 ⟶ 4,356:
=={{header|Fantom}}==
<
{
public static Void main ()
Line 3,783 ⟶ 4,372:
}
}
}</
=={{header|FBSL}}==
'''No 'MOD 15' needed.'''
<
DIM numbers AS STRING
Line 3,803 ⟶ 4,392:
NEXT
PAUSE</
{{out}}
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz 16 17 Fizz 19 Buzz Fiz
Line 3,812 ⟶ 4,401:
98 Fizz Buzz
Press any key to continue...
=={{header|Fe}}==
There is no built-in ''mod'' function, but you can add it via the C API.
<syntaxhighlight lang="c">
static fe_Object *mod(fe_Context *ctx, fe_Object *args) {
fe_Number n = fe_tonumber(ctx, fe_nextarg(ctx, &args));
return fe_number(ctx, fmod(n, fe_tonumber(ctx, fe_nextarg(ctx, &args))));
}
</syntaxhighlight>
Then, you can solve 'FizzBuzz' the traditional way:
<syntaxhighlight lang="clojure">
(= i 0)
(while (< i 100)
(= i (+ i 1))
(print
(if (is (mod i 15) 0) "FizzBuzz"
(is (mod i 3) 0) "Fizz"
(is (mod i 5) 0) "Buzz"
i)))
</syntaxhighlight>
Of course, you can solve this without ''mod'':
<syntaxhighlight lang="clojure">
(= i 0)
(= fizz 0)
(= buzz 0)
(= fizzbuzz 0)
(while (< i 100)
(= i (+ i 1))
(= fizz (+ fizz 1))
(= buzz (+ buzz 1))
(= fizzbuzz (+ fizzbuzz 1))
; check and reset counters
(print
(if (is fizzbuzz 15) (do (= fizzbuzz 0) (= fizz 0) (= buzz 0) "fizzbuzz")
(is fizz 3) (do (= fizz 0) "fizz")
(is buzz 5) (do (= buzz 0) "buzz")
i)))
</syntaxhighlight>
=={{header|Fennel}}==
<
(print (if (= (% i 15) 0) :FizzBuzz
(= (% i 3) 0) :Fizz
(= (% i 5) 0) :Buzz
i)))</
Use pattern matching and recursive function:
<
(print (match [(% from 3) (% from 5)]
[0 0] :FizzBuzz
Line 3,829 ⟶ 4,457:
(fizz-buzz (+ from 1) to)))
(fizz-buzz 1 100)</
Alternative matching pattern:{{trans|D}}
<
(print (match (% i 15)
0 :FizzBuzz
(where (or 3 6 9 12)) :Fizz
(where (or 5 10) :Buzz
_ i)))</
=={{header|FOCAL}}==
<tt>FITR</tt> is a built-in function that truncates a floating-point number to an integer. Note that FOCAL uses an arithmetic (three-way) <tt>IF</tt> statement, rather like early Fortran.
<
01.20 QUIT
Line 3,855 ⟶ 4,483:
02.90 TYPE "Buzz" !
02.95 RETURN
02.99 TYPE %3, I, !</
=={{header|Fermat}}==
<
for i = 1 to 100 do if i|15=0 then !'FizzBuzz ' else if i|5=0 then !'Buzz ' else if i|3=0 then !'Fizz ' else !i;!' ' fi fi fi od</
{{out}}<pre>
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</pre>
=={{header|Fish}}==
See [[FizzBuzz/EsoLang#Fish]]
=={{header|Forth}}==
===table-driven===
<
: buzz ( n -- ) drop ." Buzz" ;
: fb ( n -- ) drop ." FizzBuzz" ;
Line 3,875 ⟶ 4,506:
' fizz , ' . , ' . ,
' fizz , ' buzz , ' . ,
' fizz , ' . , ' . ,</
===or the classic approach===
<
0 pad c!
dup 3 mod 0= if s" Fizz" pad place then
Line 3,885 ⟶ 4,516:
: zz ( n -- )
1+ 1 do i .fizzbuzz cr loop ;
100 zz</
===the well factored approach===
SYNONYM is a Forth200x word.
<
: Fizz? ( n -- ? ) 3 MOD 0= DUP IF ." Fizz" THEN ;
Line 3,897 ⟶ 4,528:
101 1 DO CR I DUP Fizz? OVER Buzz? OR NOT ?print LOOP ;
FizzBuzz</
===the unrolled approach===
<
: f ( n -- n+1 ) ." Fizz " 1+ ;
: b ( n -- n+1 ) ." Buzz " 1+ ;
Line 3,906 ⟶ 4,537:
: fb15 ( n -- n+15 ) fb10 n f n n fb ;
: fb100 ( n -- n+100 ) fb15 fb15 fb15 fb15 fb15 fb15 fb10 ;
: .fizzbuzz ( -- ) 1 fb100 drop ;</
=={{header|Fortran}}==
In ANSI FORTRAN 77 or later use structured IF-THEN-ELSE (example uses some ISO Fortran 90 features):
<
integer :: i
Line 3,920 ⟶ 4,551:
end if
end do
end program fizzbuzz_if</
This example uses If statements to print "Fizz" and "Buzz" next to each other if the number is divisible by 3 and 5 by waiting to use a line break until after the If statements.
<
implicit none
integer :: i = 1
Line 3,933 ⟶ 4,564:
end do
end program FizzBuzz
</syntaxhighlight>
In ISO Fortran 90 or later use SELECT-CASE statement:
<
integer :: i
Line 3,946 ⟶ 4,577:
end select
end do
end program fizzbuzz_select</
=={{header|FreeBASIC}}==
Line 3,952 ⟶ 4,583:
=={{header|Frege}}==
<
pattern = zipWith (++) (gen 3 "fizz") (gen 5 "buzz")
fizzbuzz = zipWith combine pattern [1..] where
Line 3,958 ⟶ 4,589:
then show number
else word
show $ take 100 fizzbuzz</
=={{header|Frink}}==
<
{
flag = false
Line 3,980 ⟶ 4,611:
println[]
}</
=={{header|FutureBasic}}==
<
long fizz, buzz, i
Line 3,996 ⟶ 4,627:
next i
HandleEvents</
Output:
Line 4,104 ⟶ 4,735:
=={{header|Fōrmulæ}}==
{{FormulaeEntry|page=https://formulae.org/?script=examples/FizzBuzz}}
'''Solution'''
[[File:Fōrmulæ - FizzBuzz 01.png]]
[[File:Fōrmulæ - FizzBuzz 01a.png]]
[[File:Fōrmulæ - FizzBuzz 02.png]]
=={{header|Gambas}}==
'''[https://gambas-playground.proko.eu/?gist=efbe83377a1eabe475d8eba13965cfde Click this link to run this code]'''
<
Dim siCount As Short
Dim sText As String
Line 4,124 ⟶ 4,759:
Next
End</
Output:
<pre>
Line 4,230 ⟶ 4,865:
=={{header|GAP}}==
<
local i;
for i in [1 .. 100] do
Line 4,243 ⟶ 4,878:
fi;
od;
end;</
=={{header|GDScript}}==
<syntaxhighlight lang="gdscript">
extends Node
func _ready():
for i in range(1, 101):
if i % 15 == 0:
print("FizzBuzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)
get_tree().quit()
</syntaxhighlight>
=={{header|Genyris}}==
<syntaxhighlight lang="genyris">
@prefix u "http://www.genyris.org/lang/utilities#"
Line 4,268 ⟶ 4,921:
fb
</syntaxhighlight>
=={{header|GFA Basic}}==
<syntaxhighlight lang="text">
' Fizz Buzz
'
Line 4,286 ⟶ 4,939:
ENDIF
NEXT i%
</syntaxhighlight>
=={{header|Gleam}}==
<syntaxhighlight lang="text">import gleam/int
import gleam/io
import gleam/iterator
Line 4,308 ⟶ 4,961:
_, _ -> int.to_string(n)
}
}</
=={{header|Go}}==
===switch/case approach===
<
import "fmt"
Line 4,329 ⟶ 4,982:
}
}
}</
===map approach===
<
import "fmt"
Line 4,341 ⟶ 4,994:
}[i%5 == 0][i%3 == 0])
}
}</
=={{header|Golfscript}}==
<
=={{header|Golo}}==
<
augment java.lang.Integer {
Line 4,363 ⟶ 5,016:
}
}
</syntaxhighlight>
=={{header|Gosu}}==
<
if (i % 3 == 0 && i % 5 == 0) {
Line 4,386 ⟶ 5,039:
print(i)
}</
One liner version (I added new lines to better readability but when you omit them it's one liner):
<
for (i in 1..100) {
print(i % 5 == 0 ? i % 3 == 0 ? "FizzBuzz" : "Buzz" : i % 3 == 0 ? "Fizz" : i)
}</
=={{header|Groovy}}==
<
=={{header|GW-BASIC}}==
Line 4,400 ⟶ 5,053:
=={{header|Hare}}==
<
use fmt;
Line 4,413 ⟶ 5,066:
};
};
</syntaxhighlight>
=={{header|Haskell}}==
Variant directly implementing the specification:
<
fizzbuzz x
| f 15 = "FizzBuzz"
Line 4,427 ⟶ 5,080:
main :: IO ()
main = mapM_ (putStrLn . fizzbuzz) [1 .. 100]</
<
fizzbuzz n =
'\n' :
Line 4,446 ⟶ 5,099:
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].
<
fizzbuzz n =
Line 4,461 ⟶ 5,114:
fizz = "Fizz"
buzz = "Buzz"</
Alternate implementation using lazy infinite lists and avoiding use of "mod":
<
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
<
fizzBuzz :: [String]
fizzBuzz =
getZipList $ go <$>
ZipList (cycle $ replicate 2 [] <> ["fizz"]) <*>
ZipList (cycle $ replicate
ZipList (show <$> [1 ..])
go :: String -> String -> String -> String
go f b n
| null f && null b = n
| otherwise = f <> b
main :: IO ()
main = mapM_ putStrLn $ take 100 fizzBuzz</
or using an applicative test:
<
fizzBuzz :: [String]
Line 4,500 ⟶ 5,155:
main :: IO ()
main = mapM_ putStrLn $ take 100 fizzBuzz
</syntaxhighlight>
Using heavy artillery (needs the mtl package):
<
import Control.Monad.State
import Control.Monad.Trans
Line 4,515 ⟶ 5,170:
when (x `mod` 5 == 0) $ tell "Buzz" >> put False
get >>= (flip when $ tell $ show x)
tell "\n"</
Using guards plus where.
<
fizzBuzz i
| fizz && buzz = "FizzBuzz"
Line 4,526 ⟶ 5,181:
buzz = i `mod` 5 == 0
main = mapM_ (putStrLn . fizzBuzz) [1..100]</
An elegant solution exploiting monoidal and applicative properties of functions:
<
fizzbuzz = max
Line 4,540 ⟶ 5,195:
divisibleBy n x = x `mod` n == 0
main = mapM_ (putStrLn . fizzbuzz) [1..100]</
And pattern matching approach:
<
(0, 0) -> "FizzBuzz"
(0, _) -> "Fizz"
Line 4,549 ⟶ 5,204:
(_, _) -> show n
main = mapM_ (putStrLn . fizzbuzz) [1..100]</
Generalised solution:
<
wordthing lst n =
if matches == [] then
Line 4,564 ⟶ 5,219:
main = do
mapM_ (putStrLn . fizzbuzz) [1..100]</
=={{header|hexiscript}}==
<
if i % 3 = 0 && i % 5 = 0; println "FizzBuzz"
elif i % 3 = 0; println "Fizz"
elif i % 5 = 0; println "Buzz"
else println i; endif
endfor</
=={{header|HicEst}}==
<
IF( MOD(i, 15) == 0 ) THEN
WRITE() "FizzBuzz"
Line 4,585 ⟶ 5,240:
WRITE() i
ENDIF
ENDDO</
Alternatively:
<
DO i = 1, 100
Line 4,595 ⟶ 5,250:
IF( string == " ") WRITE(Text=string) i
WRITE() string
ENDDO</
=={{header|HolyC}}==
<
for (i = 1; i <= 100; i++) {
if (!(i % 15))
Line 4,609 ⟶ 5,264:
Print("%d", i);
Print("\n");
}</
=={{header|Hoon}}==
<
|= [^ ~ ~]
:- %noun
Line 4,622 ⟶ 5,277:
[& |] "Fizz"
[| &] "Buzz"
==</
=={{header|Huginn}}==
<
main( argv_ ) {
Line 4,647 ⟶ 5,302:
}
return ( 0 );
}</
=={{header|Hy}}==
<
[(not (% i 15)) "FizzBuzz"]
[(not (% i 5)) "Buzz"]
[(not (% i 3)) "Fizz"]
[True i])))</
=={{header|i}}==
<
for each 1 to 100
if i % 15 = 0
Line 4,670 ⟶ 5,325:
end
end
}</
=={{header|Icon}} and {{header|Unicon}}==
<
procedure main()
every i := 1 to 100 do
Line 4,684 ⟶ 5,339:
else
write(i)
end</
<
procedure main()
every i := 1 to 100 do
write((i % 15 = 0 & "FizzBuzz") | (i % 5 = 0 & "Buzz") | (i % 3 = 0 & "Fizz") | i)
end</
<
procedure main()
every i := 1 to 100 do
Line 4,699 ⟶ 5,354:
default: i
})
end</
<
procedure main()
every i := 1 to 100 do {
Line 4,712 ⟶ 5,367:
write(s)
}
end</
<
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</
<
procedure main()
every i := 1 to 100 do {
Line 4,725 ⟶ 5,380:
write(("" ~= s) | i)
}
end</
=={{header|Idris}}==
<
fizzBuzz : Nat -> String
fizzBuzz n = if (n `modNat` 15) == 0 then "FizzBuzz"
Line 4,736 ⟶ 5,391:
main : IO ()
main = sequence_ $ map (putStrLn . fizzBuzz) [1..100]</
=={{header|Inform 6}}==
<
for (i = 1: i <= 100: i++) {
if (i % 3 == 0)
if (i % 5 == 0)
if (i % 3 ~= 0 && i % 5 ~= 0)
print i;
print "^";
}
];</
=={{header|Inform 7}}==
Line 4,754 ⟶ 5,411:
(Does not work in the current version of Inform 7)
<
When play begins:
Line 4,767 ⟶ 5,424:
if printed is false, say N;
say ".";
end the story.</
(Version which is less "programmy", and more in the natural English style of interactive fiction.)
<
To say the name:
Line 4,786 ⟶ 5,443:
end if.
When play begins: count. Use no scoring.</
=={{header|Insitux}}==
<syntaxhighlight lang="insitux">(function fizzbuzz n
(match (map (rem n) [3 5])
[0 0] "FizzBuzz"
[0 _] "Fizz"
[_ 0] "Buzz"
n))
(loop 100 i
(-> i inc fizzbuzz print))</syntaxhighlight>
=={{header|Io}}==
Here's one way to do it:
<
if(a % 15 == 0) then(
"FizzBuzz" println
Line 4,800 ⟶ 5,468:
a println
)
)</
And here's a port of the Ruby version, which I personally prefer:
<
for(n, 1, 100,
if(a = (n % 3) == 0, "Fizz" print);
Line 4,808 ⟶ 5,476:
if(a not and b not, n print);
"\n" print
)</
And here is another more idiomatic version:
<
fb := list (
if (n % 3 == 0, "Fizz"),
Line 4,816 ⟶ 5,484:
if (fb isEmpty, n, fb join) println
)</
=={{header|Ioke}}==
<
cond(
(x % 15) zero?, "FizzBuzz" println,
Line 4,825 ⟶ 5,493:
(x % 5) zero?, "Buzz" println
)
)</
=={{header|Iptscrae}}==
<
1 a =
{
Line 4,837 ⟶ 5,505:
a ++
}
{ a 100 <= } WHILE</
=={{header|IS-BASIC}}==
See [[FizzBuzz/Basic]]
=={{header|J}}==
Line 4,848 ⟶ 5,519:
Solution _1: Using agenda (@.) as a switch:
<syntaxhighlight lang="j">
classify =: +/@(1 2 * 0 = 3 5&|~)
(":@]`('Fizz'"_)`('Buzz'"_)`('FizzBuzz'"_) @. classify "0) >:i.100
</syntaxhighlight>
Solution 0
<
Solution 1
<
Buzz=: 'Buzz' #~ 0 = 5&|
FizzBuzz=: ": [^:('' -: ]) Fizz,Buzz
FizzBuzz"0 >: i.100</
Solution 2 (has taste of table-driven template programming)
<
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</
Solution 3 (depends on an obsolete feature of @ in f`g`h@p)
<
'`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</
Solution 4 (relatively concise):
<
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 Fiz...</
Here's some intermediate results for subexpressions of this last version (but with a shorter list of numbers):
<
0 1 2 3 4 5 6 7 8 9
(3 5 |/ ])i.10
Line 4,917 ⟶ 5,588:
└─┴─┴────┴─┴────┴────┴─┴─┴────┘
;:inv}.(":&.> [^:(0 = #@])&.> [: ,&.>/ (;:'Fizz Buzz') #&.>~0=3 5 |/ ])i.10
1 2 Fizz 4 Buzz Fizz 7 8 Fizz</
=={{header|Janet}}==
<
(loop [i :range [1 101]
:let [fizz (zero? (% i 3))
Line 4,929 ⟶ 5,600:
buzz "buzz"
i)))
</syntaxhighlight>
=={{header|Java}}==
<
public class FizzBuzz {
public static void main(String[] args) {
Line 4,948 ⟶ 5,619:
}
}
</syntaxhighlight>
'''Or: '''
<
public class FizzBuzz {
public static void main(String[] args) {
Line 4,968 ⟶ 5,639:
}
}
</syntaxhighlight>
'''Or: '''
<
public class FizzBuzz {
public static void main(String[] args) {
Line 4,980 ⟶ 5,651:
}
}
</syntaxhighlight>
'''Or: '''
<syntaxhighlight lang="java">
import java.util.stream.IntStream;
class FizzBuzzJdk12 {
public static void main(String[] args) {
IntStream.range(1,101)
.mapToObj(i->switch (i%15) {
case 0 -> "FizzBuzz";
case 3, 6, 9, 12 -> "Fizz";
case 5, 10 -> "Buzz";
default -> Integer.toString(i);
})
.forEach(System.out::println)
;
}
}
</syntaxhighlight>
'''Or: '''
<syntaxhighlight lang="java">
import java.util.stream.IntStream;
class FizzBuzzJdk12 {
static final int FIZZ_FLAG = 0x8000_0000;
static final int BUZZ_FLAG = 0x4000_0000;
static final int FIZZ_BUZZ_FLAG = FIZZ_FLAG|BUZZ_FLAG;
static final int[] FLAGS = new int[] {
FIZZ_BUZZ_FLAG|0, 1, 2, FIZZ_FLAG|3, 4,
BUZZ_FLAG|5, FIZZ_FLAG|6, 7, 8, FIZZ_FLAG|9,
BUZZ_FLAG|10, 11, FIZZ_FLAG|12, 13, 14
};
public static void main(String[] args) {
IntStream.iterate(0,i->++i)
.flatMap(i -> IntStream.range(0,15).map(j->FLAGS[j]+15*i))
.mapToObj(
// JDK12 switch expression ...
n-> switch(n & FIZZ_BUZZ_FLAG) {
case FIZZ_BUZZ_FLAG -> "fizzbuzz";
case FIZZ_FLAG -> "fizz";
case BUZZ_FLAG -> "buzz";
default -> Integer.toString(~FIZZ_BUZZ_FLAG & n);
}
)
.skip(1)
.limit(100)
.forEach(System.out::println)
;
}
}
</syntaxhighlight>
=={{header|JavaScript}}==
Line 4,986 ⟶ 5,706:
===ES5===
<
var i, output;
for (i = 1; i < 101; i += 1) {
Line 4,994 ⟶ 5,714:
console.log(output || i);//empty string is false, so we short-circuit
}
};</
Alternate version with ghetto pattern matching
<
console.log({
truefalse: 'Fizz',
Line 5,003 ⟶ 5,723:
truetrue: 'FizzBuzz'
}[(i%3==0) + '' + (i%5==0)] || i)
}</
Or very tersely:
<
Or with even less characters:
<
Or, in a more functional style, without mutations
<
return i ? rng(i - 1).concat(i) : []
})(100).map(
Line 5,022 ⟶ 5,742:
)
}
).join(' ')</
===ES6===
<
// FIZZBUZZ --------------------------------------------------------------
Line 5,060 ⟶ 5,780:
map(fizzBuzz, enumFromTo(1, 100))
);
})();</
A functional implementation:
<
const fizzBuzz = num => factors.map(([factor,text]) => (num % factor)?'':text).join('') || num
const range1 = x => [...Array(x+1).keys()].slice(1)
const outputs = range1(100).map(fizzBuzz)
console.log(outputs.join('\n'))</
Line 5,075 ⟶ 5,795:
{{Trans|Python}}
{{Trans|Haskell}}
<
'use strict';
Line 5,259 ⟶ 5,979:
// MAIN ---
return main();
})();</
=={{header|Joy}}==
The following program first defines a function "out", that handles the Fizz / Buzz logic, and then loops from 1 to 100 mapping the function onto each number, and printing ("put") the output.
<syntaxhighlight lang=
[[ 3 rem null] "Fizz"]
[[ 5 rem null] "Buzz"]
Line 5,272 ⟶ 5,992:
=={{header|jq}}==
<
| if . % 15 == 0 then "FizzBuzz"
elif . % 5 == 0 then "Buzz"
elif . % 3 == 0 then "Fizz"
else .
end</
Another solution:
<
(select(. % 3 == 0) | "Fizz"),
(select(. % 5 == 0) | "Buzz")
) // tostring] | join("")
</syntaxhighlight>
=={{header|Julia}}==
{{works with|Julia|
One basic solution:
<
if i % 15 == 0
println("FizzBuzz")
Line 5,301 ⟶ 6,021:
println(i)
end
end</
Another possible solution:
<
A 3rd possible solution:
<
for i in 1:100 println(fb(i)) end</
A 4th one:
<
A fifth (DRY, Don't Repeat Yourself) possible solution:
<
msg = "Fizz" ^ (i % 3 == 0) * "Buzz" ^ (i % 5 == 0)
println(isempty(msg) ? i : msg)
end</
=={{header|K}}==
===Solution 0===
<
===Solution 1===
<syntaxhighlight lang="k">
fizzbuzz:{:[0=x!15;`0:,"FizzBuzz";0=x!3;`0:,"Fizz";0=x!5;`0:,"Buzz";`0:,$x]}
fizzbuzz' 1+!100
</syntaxhighlight>
===Solution 2===
<
v:1+!x
i:(&0=)'v!/:3 5 15
Line 5,337 ⟶ 6,057:
@[r;i 2;{"FizzBuzz"}]}
`0:$fizzbuzz 100</
===Solution 3===
For kona: <
For k6 and oK, change <code>x!'3 5</code> to <code>3 5!'x</code>.
Line 5,347 ⟶ 6,067:
This will only work up to 100 because Kamailio terminates all while loops after 100 iterations.
<
log_stderror=yes
loadmodule "pv"
Line 5,366 ⟶ 6,086:
$var(i) = $var(i) + 1;
}
}</
=={{header|Kaya}}==
<
program fizzbuzz;
Line 5,388 ⟶ 6,108:
Void main() {
fizzbuzz(100);
}</
=={{header|KL1}}==
<
:- module main.
Line 5,429 ⟶ 6,149:
display(Rest).
display([]).
</syntaxhighlight>
=={{header|Klong}}==
<syntaxhighlight lang="k">
{:[0=x!15;:FizzBuzz:|0=x!5;:Buzz:|0=x!3;:Fizz;x]}'1+!100
</syntaxhighlight>
=={{header|Kotlin}}==
===Imperative solution===
<
for (number in 1..100) {
println(
Line 5,450 ⟶ 6,170:
)
}
}</
===Functional solution 1===
<
fun fizzBuzz(x: Int) = if (x % 15 == 0) "FizzBuzz" else x.toString()
fun fizz(x: Any) = if (x is Int && x % 3 == 0) "Buzz" else x
Line 5,459 ⟶ 6,179:
(1..100).map { fizzBuzz(it) }.map { fizz(it) }.map { buzz(it) }.forEach { println(it) }
}</
===Functional solution 2===
<
fun fizz(x: Pair<Int, StringBuilder>) = if(x.first % 3 == 0) x.apply { second.append("Fizz") } else x
fun buzz(x: Pair<Int, StringBuilder>) = if(x.first % 5 == 0) x.apply { second.append("Buzz") } else x
Line 5,472 ⟶ 6,192:
.map { none(it) }
.forEach { println(it) }
}</
===Short version with mapOf===
<
fun fizzBuzz() {
(1..100).forEach { println(mapOf(0 to it, it % 3 to "Fizz", it % 5 to "Buzz", it % 15 to "FizzBuzz")[0]) }
}
</syntaxhighlight>
=={{header|KQL}}==
<
range i from 1 to 100 step 1
| project Result =
Line 5,491 ⟶ 6,211:
tostring(i)
)
</syntaxhighlight>
=={{header|KSI}}==
<
`plain
[1 100] `for pos : n ~
Line 5,502 ⟶ 6,222:
(out `or n) #write_ln #
;
</syntaxhighlight>
=={{header|LabVIEW}}==
Line 5,509 ⟶ 6,229:
=={{header|Lambdatalk}}==
<syntaxhighlight lang="scheme">
1. direct:
Line 5,543 ⟶ 6,263:
-> same as above.
</syntaxhighlight>
=={{header|
<syntaxhighlight lang="lang">
$i = 1
while($i <= 100) {
if($i % 15 == 0) {
fn.println(FizzBuzz)
}elif($i % 5 == 0) {
fn.println(Buzz)
}elif($i % 3 == 0) {
fn.println(Fizz)
}else {
fn.println($i)
}
$i += 1
}
</syntaxhighlight>
=={{
<syntaxhighlight lang
for i of 100 {
writeln switch(0; i rem 15: "FizzBuzz"; i rem 5: "Buzz"; i rem 3: "Fizz"; i)
}
</syntaxhighlight>
=={{header|Lasso}}==
<
select ((#i % 3 == 0 ? 'Fizz' | '') + (#i % 5 == 0 ? 'Buzz' | '') || #i)</
=={{header|LaTeX}}==
Line 5,563 ⟶ 6,298:
{{libheader|intcalc}}
This version uses the ifthen and intcalc packages. There sure are more native solutions including solutions in plain TeX, but for me this is a readable and comprehensible one.
<
\usepackage{ifthen}
\usepackage{intcalc}
Line 5,581 ⟶ 6,316:
\begin{document}
\fizzBuzz{101}
\end{document}</
=={{header|LDPL}}==
<syntaxhighlight lang="ldpl">data:
i is number
n is number
procedure:
for i from 1 to 101 step 1 do
modulo i by 15 in n
if n is equal to 0 then
display "FizzBuzz" lf
continue
end if
modulo i by 5 in n
if n is equal to 0 then
display "Buzz" lf
continue
end if
modulo i by 3 in n
if n is equal to 0 then
display "Fizz" lf
continue
end if
display i lf
repeat
</syntaxhighlight>
=={{header|Lean}}==
Lean 4:
<syntaxhighlight lang="lean">
def fizz : String :=
"Fizz"
def buzz : String :=
"Buzz"
def newLine : String :=
"\n"
def isDivisibleBy (n : Nat) (m : Nat) : Bool :=
match m with
| 0 => false
| (k + 1) => (n % (k + 1)) = 0
def getTerm (n : Nat) : String :=
if (isDivisibleBy n 15) then (fizz ++ buzz)
else if (isDivisibleBy n 3) then fizz
else if (isDivisibleBy n 5) then buzz
else toString (n)
def range (a : Nat) (b : Nat) : List (Nat) :=
match b with
| 0 => []
| m + 1 => a :: (range (a + 1) m)
def getTerms (n : Nat) : List (String) :=
(range 1 n).map (getTerm)
def addNewLine (accum : String) (elem : String) : String :=
accum ++ elem ++ newLine
def fizzBuzz : String :=
(getTerms 100).foldl (addNewLine) ("")
def main : IO Unit :=
IO.println (fizzBuzz)
#eval main
</syntaxhighlight>
=={{header|Liberty BASIC}}==
Line 5,587 ⟶ 6,394:
=={{header|LIL}}==
<
for {set i 1} {$i <= 100} {inc i} {
set show ""
Line 5,594 ⟶ 6,401:
if {[expr [length $show] == 0]} {set show $i}
print $show
}</
{{out}}
Line 5,616 ⟶ 6,423:
=={{header|LiveCode}}==
<
switch
case i mod 15 = 0
Line 5,631 ⟶ 6,438:
end switch
end repeat
put fizzbuzz</
=={{header|LiveScript}}==
See: http://livescript.net/blog/fizzbuzzbazz.html
<
=={{header|LLVM}}==
<
; source_filename = "fizzbuzz.c"
; target datalayout = "e-m:w-i64:64-f80:128-n8:16:32:64-S128"
Line 5,738 ⟶ 6,545:
!0 = !{i32 1, !"wchar_size", i32 2}
!1 = !{i32 7, !"PIC Level", i32 2}
!2 = !{!"clang version 6.0.1 (tags/RELEASE_601/final)"}</
=={{header|Lobster}}==
<
forbias(100, 1) i:
fb := (i % 3 == 0 and "fizz" or "") +
(i % 5 == 0 and "buzz" or "")
print fb.length and fb or "" + i</
=={{header|Logo}}==
<
output cond [ [[equal? 0 modulo :n 15] "FizzBuzz]
[[equal? 0 modulo :n 5] "Buzz]
Line 5,756 ⟶ 6,563:
end
repeat 100 [print fizzbuzz #]</
"cond" was undefined in Joshua Bell's online interpreter. So here is a version that works there. It also works in UCB logo by using # instead of "repcount". This version also factors away modulo 15:
<
make "c "
if equal? 0 modulo :n 5 [make "c "Buzz]
Line 5,765 ⟶ 6,572:
end
repeat 100 [print fizzbuzz repcount]</
Lhogho can use the above code, except that 'modulo' must be replaced with 'remainder'.
Line 5,772 ⟶ 6,579:
=={{header|LSE}}==
<
10 CHAINE FB
20 FAIRE 45 POUR I_1 JUSQUA 100
Line 5,780 ⟶ 6,587:
50 TERMINER
100 PROCEDURE &MOD(A,B) LOCAL A,B
110 RESULTAT A-B*ENT(A/B)</
=={{header|Lua}}==
===If/else Ladder===
<
if i % 15 == 0 then
print("FizzBuzz")
Line 5,794 ⟶ 6,601:
print(i)
end
end</
===Concatenation===
<
output = ""
if i % 3 == 0 then
Line 5,808 ⟶ 6,615:
end
print(output)
end</
===Quasi bit field===
<
for i = 1, 100 do
print(word[(i % 3 == 0 and 1 or 0) + (i % 5 == 0 and 2 or 0)] or i)
end</
===Lookup table===
<
[0] = "FizzBuzz",
[3] = "Fizz",
Line 5,830 ⟶ 6,637:
for i = 1, 100 do
print(t[i%15] or i)
end</
=== Metatable insertion ===
Sets any numeric key to its fizzbuzz value so that fizzbuzz[30] is "fizzbuzz"
<syntaxhighlight lang="lua">local mt = {
__newindex = (function (t, k, v)
if type(k) ~= "number" then rawset(t, k, v)
elseif 0 == (k % 15) then rawset(t, k, "fizzbuzz")
elseif 0 == (k % 5) then rawset(t, k, "fizz")
elseif 0 == (k % 3) then rawset(t, k, "buzz")
else rawset(t, k, k) end
return t[k]
end)
}
local fizzbuzz = {}
setmetatable(fizzbuzz, mt)
for i=1,100 do fizzbuzz[i] = i end
for i=1,100 do print(fizzbuzz[i]) end
</syntaxhighlight>
=== Fast Version without Modulo ===
<
#!/usr/bin/env luajit
local to=arg[1] or tonumber(arg[1]) or 100
Line 5,854 ⟶ 6,681:
io.write(", ")
end
</syntaxhighlight>
{{out}}
Line 5,863 ⟶ 6,690:
=={{header|Luck}}==
<
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)
)</
=={{header|M2000 Interpreter}}==
<syntaxhighlight lang="m2000 interpreter">
\\ one line, hard to read
For i=1 to 100 {If i mod 3=0 Then {if i mod 5=0 Then Print "FizzBuzz", Else Print "Fizz",} Else {if i mod 5=0 Then Print "Buzz", else print i, } } : Print
Line 5,890 ⟶ 6,717:
If a$<>"" Then Print a$, else Print i,
End Sub
</syntaxhighlight>
=={{header|M4}}==
<
`ifelse($#,0,``$0'',
`ifelse(eval($2<=$3),1,
Line 5,902 ⟶ 6,729:
`ifelse(eval(x%3==0),1,Fizz,
`ifelse(eval(x%5==0),1,Buzz,x)')')
')</
=={{header|MACRO-11}}==
<syntaxhighlight lang="macro11"> .TITLE FIZBUZ
.MCALL .TTYOUT,.EXIT
FIZBUZ::MOV #1,R2 ; COUNTER
MOV #3,R3 ; FIZZ COUNTER
MOV #5,R4 ; BUZZ COUNTER
NUMBER: CLR R5
CHKFIZ: DEC R3
BNE CHKBUZ
MOV #FIZZ,R1
JSR PC,PRSTR
MOV #3,R3
INC R5
CHKBUZ: DEC R4
BNE CHKNUM
MOV #BUZZ,R1
JSR PC,PRSTR
MOV #5,R4
INC R5
CHKNUM: TST R5
BNE NEXNUM
MOV R2,R0
JSR PC,PR0
NEXNUM: MOV #NL,R1
JSR PC,PRSTR
INC R2
CMP R2,#^D100
BLE NUMBER
.EXIT
; STRING DATA
FIZZ: .ASCIZ /FIZZ/
BUZZ: .ASCIZ /BUZZ/
NL: .BYTE 15,12,0
.EVEN
; PRINT NUMBER IN R0 AS DECIMAL
PR0: MOV R2,-(SP)
MOV #4$,R1
1$: MOV #-1,R2
2$: INC R2
SUB #12,R0
BCC 2$
ADD #72,R0
MOVB R0,-(R1)
MOV R2,R0
BNE 1$
3$: MOVB (R1)+,R0
.TTYOUT
BNE 3$
MOV (SP)+,R2
RTS PC
.ASCII /...../
4$: .BYTE 0
; PRINT STRING IN R1
PRSTR: MOVB (R1)+,R0
.TTYOUT
BNE PRSTR
RTS PC
.END FIZBUZ</syntaxhighlight>
=={{header|MAD}}==
<syntaxhighlight lang="mad"> NORMAL MODE IS INTEGER
VECTOR VALUES FIZZ = $4HFIZZ*$
VECTOR VALUES BUZZ = $4HBUZZ*$
VECTOR VALUES FIBU = $8HFIZZBUZZ*$
VECTOR VALUES NUM = $I2*$
INTERNAL FUNCTION REM.(A,B) = A-(A/B)*B
THROUGH LOOP, FOR I = 1, 1, I .G. 100
WHENEVER REM.(I,15).E.0
PRINT FORMAT FIBU
OR WHENEVER REM.(I,5).E.0
PRINT FORMAT BUZZ
OR WHENEVER REM.(I,3).E.0
PRINT FORMAT FIZZ
OTHERWISE
PRINT FORMAT NUM,I
LOOP END OF CONDITIONAL
END OF PROGRAM</syntaxhighlight>
=={{header|make}}==
{{works with|BSD make}}
{{libheader|jot}}
<
MOD5 = 0
ALL != jot 100
Line 5,934 ⟶ 6,842:
. endif
.endfor</
=={{header|Maple}}==
One line:
<
With a fizzbuzz function defined:
<
for i to 100 do fizzbuzz1(i); od;</
Using piecewise:
<
for i to 100 do fizzbuzz2(i); od;</
Using conventional if/then branches:
<
r:=map2(modp,n,[3,5]);
if r=[0,0] then "FizzBuzz"
Line 5,953 ⟶ 6,861:
else n fi;
end proc:
for i to 100 do fizzbuzz3(i); od;</
=={{header|Mathematica}} / {{header|Wolfram Language}}==
<
Using rules,
<
buzz[i_] := Mod[i, 5] == 0
Range[100] /. {i_ /; fizz[i]&&buzz[i] :> "FizzBuzz", \
i_?fizz :> "Fizz", i_?buzz :> "Buzz"}</
Using rules, but different approach:
<
f[n_ /; Mod[n, 15] == 0] := "FizzBuzz";
f[n_ /; Mod[n, 3] == 0] := "Fizz";
Line 5,969 ⟶ 6,877:
f[n_] := n;
f[Range[100]]</
An extendible version using Table
<
Table[If[Divisible[i, First@nw], Last@nw, ""],
{nw, {{3, "Fizz"}, {5, "Buzz"}}}]],
{i, 1, 100}]</
Another one-liner using Map (the /@ operator shorthand of it) and a pure function with a very readable Which
<
Additional examples using DownValue pattern matching, the first without Mod'ing 15:
<syntaxhighlight lang="mathematica">f[n_] := f[n, Mod[n, {3, 5}]]
f[_, {0, 0}] := "FizzBuzz"
f[_, {0, _}] := "Fizz"
f[_, {_, 0}] := "Buzz"
f[n_, {_, _}] := n
f /@ Range[100]</syntaxhighlight>
<syntaxhighlight lang="mathematica">f[n_] := f[n, Mod[n, 15]]
f[_, 0] := "FizzBuzz"
f[n_, _] := f[n, Mod[n, {3, 5}]]
f[_, {0, _}] := "Fizz"
f[_, {_, 0}] := "Buzz"
f[n_, {_, _}] := n
f /@ Range[100]</syntaxhighlight>
=={{header|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).
<
for i = (1:100)
if mod(i,15) == 0
Line 5,993 ⟶ 6,920:
end
fprintf('\n');
end</
Here's a more extendible version that uses disp() to print the output:
<
nums = [3, 5];
words = {'fizz', 'buzz'};
Line 6,011 ⟶ 6,938:
end
end
end</
'''straightforward'''
<syntaxhighlight lang="matlab">
x = string(1:100);
x(3:3:$) = 'Fizz';
x(5:5:$) = 'Buzz';
x(3*5:3*5:$) = 'FizzBuzz'
</syntaxhighlight>
=={{header|Maxima}}==
<
if mod(n, 15) = 0 then (sprint("FizzBuzz"), newline())
elseif mod(n, 3) = 0 then (sprint("Fizz"), newline())
elseif mod(n,5) = 0 then (sprint("Buzz"), newline())
else (sprint(n), newline());</
=={{header|MAXScript}}==
<
(
case of
Line 6,030 ⟶ 6,965:
default: (print i)
)
)</
=={{header|MEL}}==
<
{
if($i % 15 == 0)
Line 6,043 ⟶ 6,978:
else
print ($i + "\n");
}</
=={{header|Mercury}}==
<
:- interface.
:- import_module io.
Line 6,076 ⟶ 7,011:
else
true
).</
=={{header|Metafont}}==
<
message if i mod 15 = 0: "FizzBuzz" &
elseif i mod 3 = 0: "Fizz" &
Line 6,085 ⟶ 7,020:
else: decimal i & fi "";
endfor
end</
=={{header|Microsoft Small Basic}}==
{{trans|GW-BASIC}}
<
For n = 1 To 100
op = ""
Line 6,104 ⟶ 7,039:
EndIf
EndFor
</syntaxhighlight>
=={{header|min}}==
{{works with|min|0.19.3}}
<
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</
=={{header|Minimal BASIC}}==
See [[FizzBuzz/Basic]]
=={{header|MiniScript}}==
<
if i % 15 == 0 then
print "FizzBuzz"
Line 6,126 ⟶ 7,064:
print i
end if
end for</
=={{header|MIPS Assembly}}==
<
#################################
# Fizz Buzz #
Line 6,204 ⟶ 7,142:
li $v0,10
syscall
</syntaxhighlight>
=={{header|Mirah}}==
<
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:
<
if (n % 15) == 0
puts "FizzBuzz"
Line 6,225 ⟶ 7,163:
puts n
end
end</
=={{header|Miranda}}==
<syntaxhighlight lang="miranda">main :: [sys_message]
main = [Stdout (lay (map fizzbuzz [1..100]))]
fizzbuzz :: num->[char]
fizzbuzz n = "FizzBuzz", if n mod 15 = 0
= "Fizz", if n mod 3 = 0
= "Buzz", if n mod 5 = 0
= show n, otherwise</syntaxhighlight>
=={{header|ML}}==
==={{header|Standard ML}}===
First using two helper functions, one for deciding what to output and another for performing recursion with an auxiliary argument j.
<
fun fbstr i =
case (i mod 3 = 0, i mod 5 = 0) of
Line 6,243 ⟶ 7,191:
fun fizzbuzz n = fizzbuzz' (n, 1)
val _ = fizzbuzz 100
end</
Second using the standard-library combinator List.tabulate and a helper function, fb, that calculates and prints the output.
<
fun fb i = let val fizz = i mod 3 = 0 andalso (print "Fizz"; true)
val buzz = i mod 5 = 0 andalso (print "Buzz"; true)
Line 6,253 ⟶ 7,201:
fun fizzbuzz n = (List.tabulate (n, fn i => (fb (i+1); print "\n")); ())
val _ = fizzbuzz 100
end</
==={{header|mLite}}===
<
fun fizzbuzz'
(x mod 15 = 0) = "FizzBuzz"
Line 6,271 ⟶ 7,219:
println ` fizzbuzz ` iota 100;
</syntaxhighlight>
=={{header|MMIX}}==
<
Ja IS $127
Line 6,336 ⟶ 7,284:
JMP 1B % repeat for next i
4H XOR t,t,t
TRAP 0,Halt,0 % exit(0)</
=={{header|Modula-2}}==
<
FROM FormatString IMPORT FormatString;
FROM Terminal IMPORT WriteString,WriteLn,ReadChar;
Line 6,384 ⟶ 7,332:
ReadChar
END Fizzbuzz.</
=={{header|Modula-3}}==
<
IMPORT IO;
Line 6,404 ⟶ 7,352:
END;
END;
END Fizzbuzz.</
=={{header|Monte}}==
<
var t := 1
while (t < top):
Line 6,421 ⟶ 7,369:
fizzBuzz(100)
</syntaxhighlight>
=={{header|MontiLang}}==
<
1 VAR i .
Line 6,447 ⟶ 7,395:
ENDIF
i 1 + VAR i .
ENDFOR</
=={{header|MoonScript}}==
<
print ((a) -> a == "" and i or a) table.concat {
i % 3 == 0 and "Fizz" or ""
i % 5 == 0 and "Buzz" or ""}</
=={{header|MUMPS}}==
<
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</
<
for i=1:1:100 do write !
. write:(i#3)&(i#5) i write:'(i#3) "Fizz" write:'(i#5) "Buzz"</
=={{header|Nanoquery}}==
<
if ((i % 3) = 0) and ((i % 5) = 0)
println "FizzBuzz"
Line 6,478 ⟶ 7,426:
println i
end
end</
=={{header|NATURAL}}==
<syntaxhighlight lang="natural">
DEFINE DATA
LOCAL
Line 6,515 ⟶ 7,463:
*
END
</syntaxhighlight>
=={{header|Neko}}==
<
while(i < 100) {
Line 6,532 ⟶ 7,480:
i ++= 1
}</
=={{header|Nemerle}}==
The naive approach:
<
using System.Console;
Line 6,554 ⟶ 7,502:
WriteLine($"$(FizzBuzz(i))")
}
}</
A much slicker approach is [http://www.dreamincode.net/forums/blog/217/entry-3539-fizzbuzz-in-nemerle/ posted here]
=={{header|NetRexx}}==
<
select
when j//15==0 then say 'FizzBuzz'
Line 6,565 ⟶ 7,513:
otherwise say j.right(4)
end
end</
=={{header|Never}}==
<
{
var i = 1;
Line 6,600 ⟶ 7,548:
0
}</
{{out}}
Line 6,635 ⟶ 7,583:
=={{header|NewLISP}}==
<
(println
(cond
Line 6,641 ⟶ 7,589:
((= 0 (% i 3)) "Fizz")
((= 0 (% i 5)) "Buzz")
('t i))))</
Solution 2.
Many of the solutions have a command to print "fizzbuzz". Since the programs can print "fizz" and "buzz", why not print "fizz" followed immediately by "buzz"? This also removes the need to check for divisibility by 15.
It would be nice to have a very easy way to know whether a word was actually printed (because we otherwise have to print the number). I mean a way that doesn't involve checking for divisibility again or setting a flag.
We want a macro or function that is somewhat like "or" but that evaluates all of the expressions even if the first yields true. Like "or", it returns a true value (a number) if any of the expressions yielded true. In newLISP, it seems that a function suffices, but in some languages a macro may be necessary because the arguments to a function are not always evaluated from left to right.
I believe that this method makes it easier to modify the program when the list of words to be printed is extended.
<syntaxhighlight lang="newlisp">
(define (try-all) ;; The arguments are in (args) or $args.
(let (cnt (length (filter true? $args)))
(if (zero? cnt) nil cnt)))
(define (fizz)
(define (say? n s) (if (= 0 (% i n)) (print s))) ;; Dynamic scoping.
(for (i 1 21)
(unless
(try-all
(say? 3 'fizz)
(say? 5 'buzz)
(say? 7 'boom)
(say? 11 'crux))
(print i))
(println)))
(fizz)
1
2
fizz
4
buzz
fizz
boom
8
fizz
buzz
crux
fizz
13
boom
fizzbuzz
16
17
fizz
19
buzz
fizzboom
</syntaxhighlight>
Solution 3.
Instead of explicitly including the numbers 3, 5, 7, etc., let's tell the computer to use the prime numbers starting with 3.
<syntaxhighlight lang="newlisp">
(define (m-prime-gen)
(fn ( , n) ;; Unused parameter n is our local variable.
;; Self-modifying code.
(until (= 1 (length (factor (setf n (++ 2))))))
n))
(define (try-all) ;; The arguments are in (args) or $args.
(let (cnt (length (filter true? $args)))
(if (zero? cnt) nil cnt)))
(define (fizz)
(define (say? n s) (if (= 0 (% i n)) (print s))) ;; Dynamic scoping.
(for (i 1 21)
(let (p (m-prime-gen))
(unless
(try-all
(say? (p) 'fizz)
(say? (p) 'buzz)
(say? (p) 'boom)
(say? (p) 'crux)
(say? (p) 'ZAP))
(print i))
(println))))
(fizz)
1
2
fizz
4
buzz
fizz
boom
8
fizz
buzz
crux
fizz
ZAP
boom
fizzbuzz
16
17
fizz
19
buzz
fizzboom
</syntaxhighlight>
=={{header|NewtonScript}}==
<
begin
if i mod 15 = 0 then
Line 6,655 ⟶ 7,712:
print(i);
print("\n")
end</
=={{header|Nickle}}==
<
void function fizzbuzz(size) {
Line 6,669 ⟶ 7,726:
}
fizzbuzz(1000);</
=={{header|Nim}}==
{{trans|Python}}
<
if i mod 15 == 0:
echo("FizzBuzz")
Line 6,681 ⟶ 7,738:
echo("Buzz")
else:
echo(i)</
===Without Modulus===
<
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</
===Using macro===
Computes everything at compile time.
<
macro FizzBuzz(N): untyped =
var source = ""
Line 6,709 ⟶ 7,766:
result = parseStmt(source)
FizzBuzz(100)</
=={{header|Nix}}==
<
with builtins;
let
Line 6,728 ⟶ 7,785:
fizzbuzz { x = x + 1; } else "");
in
fizzbuzz { }</
=={{header|Nu}}==
<syntaxhighlight lang="nu">
(1..100
| each {|i| $"(if $i mod 3 == 0 {"Fizz"})(if $i mod 5 == 0 {"Buzz"})"
| if ($in == "") {$i} else {$in}}
| str join "\n")
</syntaxhighlight>
=={{header|Oberon-2}}==
<
IMPORT Out;
Line 6,750 ⟶ 7,815:
Out.Ln
END
END FizzBuzz.</
=={{header|Objeck}}==
<
class Fizz {
function : Main(args : String[]) ~ Nil {
Line 6,772 ⟶ 7,837:
}
}
}</
=={{header|Objective-C}}==
<
#import <Foundation/Foundation.h>
Line 6,790 ⟶ 7,855:
}
}
}</
=={{header|OCaml}}==
Line 6,796 ⟶ 7,861:
Idiomatic OCaml to solve the stated problem:
<
match i mod 3, i mod 5 with
0, 0 -> "FizzBuzz"
Line 6,804 ⟶ 7,869:
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:
<
let (=>) cond f a = if cond then f a else a
let append s a = a^s
Line 6,816 ⟶ 7,881:
|> (i mod 5 = 0 => append "Buzz")
|> (function "" -> string_of_int i
| s -> s)</
=={{header|Octave}}==
<
if ( mod(i,15) == 0 )
disp("FizzBuzz");
Line 6,829 ⟶ 7,894:
disp(i)
endif
endfor</
=={{header|Oforth}}==
<
| i |
100 loop: i [
Line 6,840 ⟶ 7,905:
i 5 mod ifZero: [ "Buzz" + ]
dup ifNull: [ drop i ] .
] ; </
=={{header|Ol}}==
<
(for-each (lambda (x)
(print (cond
Line 6,855 ⟶ 7,920:
x))))
(iota 100))
</syntaxhighlight>
=={{header|Onyx (wasm)}}==
<syntaxhighlight lang="C">
use core { * }
fizzbuzz :: (len: u32) -> void {
for i in 1..len+1 {
msg : str;
if (i%3 == 0 && i%5 == 0) { msg = "FizzBuzz !!!"; }
elseif (i%3 == 0) { msg = "Fizz"; }
elseif (i%5 == 0) { msg = "Buzz"; }
else { msg = tprintf("{}", i); }
printf("{}\n", msg);
}
}
main :: () {
fizzbuzz(100);
}
</syntaxhighlight>
=={{header|OOC}}==
<
if(n % 3 == 0) {
printf("Fizz")
Line 6,880 ⟶ 7,966:
println()
}
}</
=={{header|Order}}==
<
// Get FB for one number
Line 6,901 ⟶ 7,987:
ORDER_PP( // foreach instead of map, to print but return nothing
8seq_for_each(8compose(8print_el, 8fizzbuzz), 8seq_iota(1, 100))
)</
=={{header|Oz}}==
<
fun {FizzBuzz X}
if X mod 15 == 0 then 'FizzBuzz'
Line 6,915 ⟶ 8,001:
for I in 1..100 do
{Show {FizzBuzz I}}
end</
=={{header|Palo Alto Tiny BASIC}}==
See [[FizzBuzz/Basic#Palo Alto Tiny BASIC|FizzBuzz/Basic]].
=={{header|PARI/GP}}==
<
print(if(n%3,
if(n%5,
Line 6,932 ⟶ 8,021:
)
))
)}</
=={{header|Pascal}}==
<
var
i: integer;
Line 6,948 ⟶ 8,037:
else
writeln(i)
end.</
=={{header|PascalABC.NET}}==
<syntaxhighlight lang="delphi">
begin
for var i:=1 to 100 do
if i mod 15 = 0 then
Print('FizzBuzz')
else if i mod 3 = 0 then
Print('Fizz')
else if i mod 5 = 0 then
Print('Buzz')
else Print(i)
end.
</syntaxhighlight>
=={{header|PDP-8 Assembly}}==
Line 6,955 ⟶ 8,058:
Runs on SimH, or any PDP-8 with an EAE
<
/--------------------------------------------------------
/THIS PROGRAM PRINTS THE INTEGERS FROM 1 TO 100 (INCL).
Line 7,089 ⟶ 8,192:
CR; LF; EOT
$
</syntaxhighlight>
Output:
Line 7,207 ⟶ 8,310:
=={{header|Peloton}}==
Variable-length padded English dialect
<
<# TEST ISITMODULUSZERO PARAMETER LITERAL>1|3</#>
<# TEST ISITMODULUSZERO PARAMETER LITERAL>1|5</#>
Line 7,215 ⟶ 8,318:
<# NEITHER><# SAY PARAMETER>1</#></#>
</#></#>
<# ITERATE FORITERATION LITERAL LITERAL>100|<# ACT USERDEFINEDROUTINE POSITION FORITERATION>__FizzBuzz|...</#> </#></
Fixed-length English dialect
<
<@ TSTMD0PARLIT>1|3</@>
<@ TSTMD0PARLIT>1|5</@>
Line 7,225 ⟶ 8,328:
<@ NTH><@ SAYPAR>1</@></@>
</@></@>
<@ ITEFORLITLIT>100|<@ ACTUDRPOSFOR>__FizzBuzz|...</@> </@></
=={{header|Perl}}==
<
use strict;
use warnings;
Line 7,238 ⟶ 8,341:
: $i % 5 == 0 ? "Buzz"
: $i;
}</
More concisely:
<
For code-golfing:
<
For array of values:
<
Cheating:
<
use feature "say";
@a = ("FizzBuzz", 0, 0, "Fizz", 0, "Buzz", "Fizz", 0, 0, "Fizz", "Buzz", 0, "Fizz");
say $a[$_ % 15] || $_ for 1..100;</
as a subroutine:
<
sub fizz_buzz {
join("\n", map {
Line 7,275 ⟶ 8,378:
}
print fizz_buzz;
</syntaxhighlight>
By transforming a list:
<
@FB1 = (1..100);
@FB2 = map{!($_%3 or $_%5)?'FizzBuzz': $_}@FB1;
Line 7,286 ⟶ 8,389:
@FB5 = map{$_."\n"}@FB4;
print @FB5;
</syntaxhighlight>
=={{header|Phix}}==
{{libheader|Phix/basics}}
{{trans|C}}
<!--<
<span style="color: #008080;">constant</span> <span style="color: #000000;">x</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{<span style="color: #008000;">"%d\n"<span style="color: #0000FF;">,<span style="color: #008000;">"Fizz\n"<span style="color: #0000FF;">,<span style="color: #008000;">"Buzz\n"<span style="color: #0000FF;">,<span style="color: #008000;">"FizzBuzz\n"<span style="color: #0000FF;">}</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i<span style="color: #0000FF;">=<span style="color: #000000;">1</span> <span style="color: #008080;">to</span> <span style="color: #000000;">100</span> <span style="color: #008080;">do</span>
<span style="color: #7060A8;">printf<span style="color: #0000FF;">(<span style="color: #000000;">1<span style="color: #0000FF;">,<span style="color: #000000;">x<span style="color: #0000FF;">[<span style="color: #000000;">1<span style="color: #0000FF;">+<span style="color: #0000FF;">(<span style="color: #7060A8;">remainder<span style="color: #0000FF;">(<span style="color: #000000;">i<span style="color: #0000FF;">,<span style="color: #000000;">3<span style="color: #0000FF;">)<span style="color: #0000FF;">=<span style="color: #000000;">0<span style="color: #0000FF;">)<span style="color: #0000FF;">+<span style="color: #000000;">2<span style="color: #0000FF;">*<span style="color: #0000FF;">(<span style="color: #7060A8;">remainder<span style="color: #0000FF;">(<span style="color: #000000;">i<span style="color: #0000FF;">,<span style="color: #000000;">5<span style="color: #0000FF;">)<span style="color: #0000FF;">=<span style="color: #000000;">0<span style="color: #0000FF;">)<span style="color: #0000FF;">]<span style="color: #0000FF;">,<span style="color: #000000;">i<span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for
<!--</
Two variants with tabulated output:
<!--<
<span style="color: #008080;">function</span> <span style="color: #000000;">f<span style="color: #0000FF;">(<span style="color: #004080;">integer</span> <span style="color: #000000;">i<span style="color: #0000FF;">)</span>
<span style="color: #004080;">integer</span> <span style="color: #000000;">idx</span> <span style="color: #0000FF;">=</span> <span style="color: #000000;">1<span style="color: #0000FF;">+<span style="color: #0000FF;">(<span style="color: #7060A8;">remainder<span style="color: #0000FF;">(<span style="color: #000000;">i<span style="color: #0000FF;">,<span style="color: #000000;">3<span style="color: #0000FF;">)<span style="color: #0000FF;">=<span style="color: #000000;">0<span style="color: #0000FF;">)<span style="color: #0000FF;">+<span style="color: #000000;">2<span style="color: #0000FF;">*<span style="color: #0000FF;">(<span style="color: #7060A8;">remainder<span style="color: #0000FF;">(<span style="color: #000000;">i<span style="color: #0000FF;">,<span style="color: #000000;">5<span style="color: #0000FF;">)<span style="color: #0000FF;">=<span style="color: #000000;">0<span style="color: #0000FF;">)</span>
Line 7,304 ⟶ 8,407:
<span style="color: #008080;">end</span> <span style="color: #008080;">function</span>
<span style="color: #7060A8;">printf<span style="color: #0000FF;">(<span style="color: #000000;">1<span style="color: #0000FF;">,<span style="color: #7060A8;">join_by<span style="color: #0000FF;">(<span style="color: #7060A8;">apply<span style="color: #0000FF;">(<span style="color: #7060A8;">tagset<span style="color: #0000FF;">(<span style="color: #000000;">100<span style="color: #0000FF;">)<span style="color: #0000FF;">,<span style="color: #000000;">f<span style="color: #0000FF;">)<span style="color: #0000FF;">,<span style="color: #000000;">10<span style="color: #0000FF;">,<span style="color: #000000;">10<span style="color: #0000FF;">)<span style="color: #0000FF;">)
<!--</
(output same as below)
<!--<
<span style="color: #004080;">sequence</span> <span style="color: #000000;">s</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">apply<span style="color: #0000FF;">(<span style="color: #004600;">true<span style="color: #0000FF;">,<span style="color: #7060A8;">sprintf<span style="color: #0000FF;">,<span style="color: #0000FF;">{<span style="color: #0000FF;">{<span style="color: #008000;">"%-8d"<span style="color: #0000FF;">}<span style="color: #0000FF;">,<span style="color: #7060A8;">tagset<span style="color: #0000FF;">(<span style="color: #000000;">100<span style="color: #0000FF;">)<span style="color: #0000FF;">}<span style="color: #0000FF;">)</span>
<span style="color: #008080;">for</span> <span style="color: #000000;">i<span style="color: #0000FF;">=<span style="color: #000000;">3</span> <span style="color: #008080;">to</span> <span style="color: #000000;">100</span> <span style="color: #008080;">by</span> <span style="color: #000000;">3</span> <span style="color: #008080;">do</span> <span style="color: #000000;">s<span style="color: #0000FF;">[<span style="color: #000000;">i<span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"Fizz "</span> <span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
Line 7,312 ⟶ 8,415:
<span style="color: #008080;">for</span> <span style="color: #000000;">i<span style="color: #0000FF;">=<span style="color: #000000;">15</span> <span style="color: #008080;">to</span> <span style="color: #000000;">100</span> <span style="color: #008080;">by</span> <span style="color: #000000;">15</span> <span style="color: #008080;">do</span> <span style="color: #000000;">s<span style="color: #0000FF;">[<span style="color: #000000;">i<span style="color: #0000FF;">]</span> <span style="color: #0000FF;">=</span> <span style="color: #008000;">"FizzBuzz"</span> <span style="color: #008080;">end</span> <span style="color: #008080;">for</span>
<span style="color: #7060A8;">printf<span style="color: #0000FF;">(<span style="color: #000000;">1<span style="color: #0000FF;">,<span style="color: #7060A8;">join_by<span style="color: #0000FF;">(<span style="color: #000000;">s<span style="color: #0000FF;">,<span style="color: #000000;">10<span style="color: #0000FF;">,<span style="color: #000000;">10<span style="color: #0000FF;">)<span style="color: #0000FF;">)
<!--</
{{out}}
<pre>
Line 7,327 ⟶ 8,430:
</pre>
Grotesquely inefficient (non-tabulated output), just for fun. Can you do worse, yet keep it semi-plausibile that someone might have actually earnestly written it?
<!--<
<span style="color: #008080;">constant</span> <span style="color: #000000;">threes</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">tagset<span style="color: #0000FF;">(<span style="color: #000000;">100<span style="color: #0000FF;">,<span style="color: #000000;">0<span style="color: #0000FF;">,<span style="color: #000000;">3<span style="color: #0000FF;">)<span style="color: #0000FF;">,</span>
<span style="color: #000000;">fives</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">tagset<span style="color: #0000FF;">(<span style="color: #000000;">100<span style="color: #0000FF;">,<span style="color: #000000;">0<span style="color: #0000FF;">,<span style="color: #000000;">5<span style="color: #0000FF;">)<span style="color: #0000FF;">,</span>
Line 7,347 ⟶ 8,450:
<span style="color: #7060A8;">printf<span style="color: #0000FF;">(<span style="color: #000000;">1<span style="color: #0000FF;">,<span style="color: #008000;">"\n"<span style="color: #0000FF;">)</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">for
<!--</
=={{header|Phixmonti}}==
<syntaxhighlight lang="Phixmonti">/# Rosetta Code problem: http://rosettacode.org/wiki/FizzBuzz
by Galileo, 10/2022 #/
100 for
dup print " " print dup
3 mod not if "Fizz" print endif
5 mod not if "Buzz" print endif
nl
endfor</syntaxhighlight>
{{out}}
<pre>1
2
3 Fizz
4
5 Buzz
6 Fizz
7
8
9 Fizz
10 Buzz
11
12 Fizz
13
14
15 FizzBuzz
16
17
18 Fizz
19
20 Buzz
21 Fizz
22
23
24 Fizz
25 Buzz
26
27 Fizz
28
29
30 FizzBuzz
31
32
33 Fizz
34
35 Buzz
36 Fizz
37
38
39 Fizz
40 Buzz
41
42 Fizz
43
44
45 FizzBuzz
46
47
48 Fizz
49
50 Buzz
51 Fizz
52
53
54 Fizz
55 Buzz
56
57 Fizz
58
59
60 FizzBuzz
61
62
63 Fizz
64
65 Buzz
66 Fizz
67
68
69 Fizz
70 Buzz
71
72 Fizz
73
74
75 FizzBuzz
76
77
78 Fizz
79
80 Buzz
81 Fizz
82
83
84 Fizz
85 Buzz
86
87 Fizz
88
89
90 FizzBuzz
91
92
93 Fizz
94
95 Buzz
96 Fizz
97
98
99 Fizz
100 Buzz
=== Press any key to exit ===</pre>
=={{header|PHL}}==
{{trans|C}}
<
extern printf;
Line 7,372 ⟶ 8,589:
return 0;
]</
=={{header|PHP}}==
===if/else ladder approach===
<
for ($i = 1; $i <= 100; $i++)
{
Line 7,388 ⟶ 8,605:
echo "$i\n";
}
?></
===Concatenation approach===
Uses PHP's concatenation operator (.=) to build the output string. The concatenation operator allows us to add data to the end of a string without overwriting the whole string. Since Buzz will always appear if our number is divisible by five, and Buzz is the second part of "FizzBuzz", we can simply append "Buzz" to our string.
In contrast to the if-else ladder, this method lets us skip the check to see if $i is divisible by both 3 and 5 (i.e. 15). However, we get the added complexity of needing to reset $str to an empty string (not necessary in some other languages), and we also need a separate if statement to check to see if our string is empty, so we know if $i was not divisible by 3 or 5.
<
for ( $i = 1; $i <= 100; ++$i )
{
Line 7,409 ⟶ 8,626:
echo $str . "\n";
}
?></
===Concatenation approach without if-s===
<
for (
$i = 0;
Line 7,418 ⟶ 8,635:
)
echo $o ? : $i, PHP_EOL;
?></
===One Liner Approach===
<
for($i = 1; $i <= 100 and print(($i % 15 ? $i % 5 ? $i % 3 ? $i : 'Fizz' : 'Buzz' : 'FizzBuzz') . "\n"); ++$i);
?></
===Compact One Liner Approach===
<
===Array One Liner Approach===
<
=={{header|Picat}}==
Line 7,436 ⟶ 8,653:
===Using a map===
<
println(fizzbuzz_map),
FB = [I : I in 1..100],
Line 7,445 ⟶ 8,662:
end
end,
println(FB).</
===Using a template for the pattern===
<
println(fizzbuzz_template1),
N = 100,
Line 7,457 ⟶ 8,674:
print(" ")
end,
nl.</
===Another version with templates===
<
println(fizzbuzz_template2),
N = 100,
Line 7,472 ⟶ 8,689:
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:
<
println(Goal),
foreach(I in 1..100)
printf("%w ", apply(Goal,I))
end,
nl.</
===Plain imperative approach: if/else===
<
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) = "Fizz", I mod 3 == 0 => true.
fb2(I) = "Buzz", I mod 5 == 0 => true.
fb2(I) = I.to_string() => true.</
===Another pattern matching approach===
<
fb3b(_I,0,0) = "FizzBuzz".
fb3b(_I,_,0) = "Buzz".
fb3b(_I,0,_) = "Fizz".
fb3b(I,_,_) = I.</
===Using cond/3 and string concatenation===
<
cond(I mod 5 == 0, "Buzz", "") ++
cond(not ((I mod 3 == 0; I mod 5==0)), I.to_string(), "").</
===Recursive function (conditions in head)===
<
print(fizzbuzz_rec),
fb5(100,[],L),
Line 7,525 ⟶ 8,742:
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===
<
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().
</syntaxhighlight>
===Planner version===
Picat has support for "classic" planning problems. The <code>planner</code> module must be imported.
<
fizzbuzz_planner =>
println(fizzbuzz_planner),
Line 7,567 ⟶ 8,784:
Move = H.to_string(),
To = H-1,
Cost = 1.</
Here we test everything.
<
fizzbuzz_map,
fizzbuzz_template1,
Line 7,583 ⟶ 8,800:
call(fizzbuzz,FB)
end,
nl.</
=={{header|PicoLisp}}==
We could simply use '[http://software-lab.de/doc/refA.html#at at]' here:
<
(prinl
(or (pack (at (0 . 3) "Fizz") (at (0 . 5) "Buzz")) N) ) )
Line 7,594 ⟶ 8,811:
# Rest of the times 'N' is printed as it loops in 'for'.
</syntaxhighlight>
Or do it the standard way:
<
(prinl
(cond
Line 7,602 ⟶ 8,819:
((=0 (% N 3)) "Fizz")
((=0 (% N 5)) "Buzz")
(T N) ) ) )</
=={{header|Piet}}==
See [[FizzBuzz/EsoLang#Piet]]
=={{header|Pike}}==
<
for(int i = 1; i <= 100; i++) {
if(i % 15 == 0) {
Line 7,617 ⟶ 8,837:
}
}
}</
=={{header|PILOT}}==
<
*loop
C :i = i + 1
Line 7,642 ⟶ 8,862:
J : *loop
*finished
END:</
=={{header|PIR}}==
{{works with|Parrot|tested with 2.4.0}}
<
.local int f
.local int mf
Line 7,679 ⟶ 8,899:
DONE:
end
.end</
=={{header|PL/I}}==
<
select;
when (mod(i,15) = 0) put skip list ('FizzBuzz');
Line 7,689 ⟶ 8,909:
otherwise put skip list (i);
end;
end;</
=={{header|PL/M}}==
<
/* DECLARE OUTPUT IN TERMS OF CP/M -
Line 7,736 ⟶ 8,956:
/* EXIT TO CP/M */
CALL BDOS(0,0);
EOF</
=={{header|PL/SQL}}==
<
for i in 1 .. 100
loop
Line 7,753 ⟶ 8,973:
end case;
end loop;
end;</
=={{header|Plain English}}==
<syntaxhighlight lang="text">
To play FizzBuzz up to a number:
Put "" into a string.
Loop.
If a counter is past the number, exit.
If the counter is evenly divisible by 3, append "Fizz" to the string.
If the counter is evenly divisible by 5, append "Buzz" to the string.
If the string is blank, append the counter then "" to the string.
Write the string to the console.
Clear the string.
Repeat.
To run:
Start up.
Play FizzBuzz up to 100.
Wait for the escape key.
Shut down.
</syntaxhighlight>
=={{header|Pointless}}==
<syntaxhighlight lang="pointless">
output =
range(1, 100)
|> map(fizzBuzz)
|> printLines
fizzBuzz(n) =
if result == "" then n else result
where result = fizzBuzzString(n)
fizzBuzzString(n) =
(if n % 3 == 0 then "Fizz" else "")
+ (if n % 5 == 0 then "Buzz" else "")
</syntaxhighlight>
=={{header|Pony}}==
<
actor Main
Line 7,773 ⟶ 9,029:
else
n.string()
end</
=={{header|Pop11}}==
<
for i from 1 to 100 do
if i rem 15 = 0 then
Line 7,788 ⟶ 9,044:
endif;
printf(str, '%s\n');
endfor;</
=={{header|PostScript}}==
<
/c false def
dup 3 mod 0 eq { (Fizz) print /c true def } if
Line 7,797 ⟶ 9,053:
c {pop}{( ) cvs print} ifelse
(\n) print
} for</
or...
<
fizzdict begin
/notmod{ ( ) cvs } def
Line 7,809 ⟶ 9,065:
1 1 100 { mod15} for
1 1 100 { dup currentdict exch known { currentdict exch get}{notmod} ifelse print (\n) print} for
end</
=={{header|Potion}}==
<
1 to 100 (a):
if (a % 15 == 0):
Line 7,821 ⟶ 9,077:
'Buzz'.
else: a. string print
"\n" print.</
=={{header|PowerShell}}==
===Straightforward, looping===
<
if ($i % 15 -eq 0) {
"FizzBuzz"
Line 7,835 ⟶ 9,091:
$i
}
}</
===Pipeline, Switch===
<
1..100 | ForEach-Object {
switch ($_) {
Line 7,844 ⟶ 9,100:
$_ { if($txt) { $txt } else { $_ }; $txt=$null }
}
}</
===Concatenation===
{{trans|C#}}
<
$s = ''
if ($_ % 3 -eq 0) { $s += "Fizz" }
Line 7,854 ⟶ 9,110:
if (-not $s) { $s = $_ }
$s
}</
===Piping, Evaluation, Concatenation===
<
1..100 | % {write-host("$(if(($_ % 3 -ne 0) -and ($_ % 5 -ne 0)){$_})$(if($_ % 3 -eq 0){"Fizz"})$(if($_ % 5 -eq 0){"Buzz"})")}
</syntaxhighlight>
===Filter, Piping, Regex Matching, Array Auto-Selection===
<
filter fizz-buzz{
@(
Line 7,877 ⟶ 9,133:
1..100 | fizz-buzz
</syntaxhighlight>
===String Manipulation with Regex===
<
(1..100 -join "`n") + "`nFizzBuzz" -replace '(?ms)(^([369]([369]|(?=0|$))|[258][147]|[147]([28]|(?=5))))(?=[05]?$.*(Fizz))|(((?<=[369])|[^369])0+|((?<=[147\s])|[^147\s])5)(?=$.*(Buzz))|FizzBuzz', '$5$9'
</syntaxhighlight>
=={{header|Processing}}==
Line 7,888 ⟶ 9,144:
Reserved variable "width" in Processing is 100 pixels by default, suitable for this FizzBuzz exercise.
Accordingly, range is pixel index from 0 to 99.
<
if (i % 3 == 0 && i % 5 == 0) {
stroke(255, 255, 0);
Line 7,906 ⟶ 9,162:
}
line(i, 0, i, height);
}</
===Console & Visualization, Ternary===
<
stroke((i % 5 == 0 && i % 3 == 0) ? #FFFF00 : (i % 5 == 0) ? #00FF00 : (i % 3 == 0) ? #FF0000 : #0000FF);
line(i, 0, i, height);
println((i % 5 == 0 && i % 3 == 0) ? "FizzBuzz!" : (i % 5 == 0) ? "Buzz" : (i % 3 == 0) ? "Fizz" : i);
}</
===Console===
<
if (i % 3 == 0) {
print("Fizz");
Line 7,925 ⟶ 9,181:
}
print("\n");
}</
===Console, "Futureproof"===
<
String output = "";
Line 7,936 ⟶ 9,192:
if(output == "") output = str(i);
println(output);
}</
All examples produce the same console output:
Line 8,046 ⟶ 9,302:
=={{header|Prolog}}==
{{works with|SWI Prolog|4.8.0}}
{{works with|Ciao Prolog|1.21.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.
<
print_item(X) :-
More conventional, doing the loop this time failure driven:
<
fizzbuzz(X) :-
fizzbuzz(X) :-
fizzbuzz(X) :- write(X).
dofizzbuzz :-
dofizzbuzz.</syntaxhighlight>
Clearer, doing the loop this time tail recursive, quite declarative:
<syntaxhighlight lang="prolog">% N /3? /5? V
fizzbuzz(_, yes, yes, 'FizzBuzz').
fizzbuzz(_, yes, no, 'Fizz').
Line 8,075 ⟶ 9,333:
% Unifies V with 'yes' if D divides evenly into N, 'no' otherwise.
divisible_by(N, D,
% Print 'Fizz', 'Buzz', 'FizzBuzz' or N as appropriate.
fizz_buzz_or_n(N) :- N > 100.
fizz_buzz_or_n(N) :- N =< 100,
divisible_by(N,
write(FB), nl,
M is N+1, fizz_buzz_or_n(M).
main :-
Using modern Prolog techniques, resulting in idiomatic, highly declarative code:
{{works with|SWI Prolog|8.2.1}} {{works with|Scryer Prolog|0.7.8}}
<
% This implementation uses modern Prolog techniques
% in order to be an idiomatic solution that uses logical purity, generality and determinism wherever possible:
Line 8,160 ⟶ 9,419:
eq_t(>, false).
</syntaxhighlight>
=={{header|PureBasic}}==
Line 8,166 ⟶ 9,425:
=={{header|Pyret}}==
<
doc: ```For positive input which is multiples of three return 'Fizz', for the multiples of five return 'Buzz'.
For numbers which are multiples of both three and five return 'FizzBuzz'. Otherwise, return the number itself.```
Line 8,183 ⟶ 9,442:
end
range(1, 101).map(fizzbuzz).each(print)</
=={{header|Python}}==
===Python2: Simple===
<
if i % 15 == 0:
print "FizzBuzz"
Line 8,195 ⟶ 9,454:
print "Buzz"
else:
print i</
===Python3: Simple===
<
if i % 15 == 0:
print("FizzBuzz")
Line 8,206 ⟶ 9,465:
print("Buzz")
else:
print(i)</
===Python: Simple - no duplication ===
<
response = ''
Line 8,218 ⟶ 9,477:
print(response or n)
</syntaxhighlight>
One liner using string concatenation:
<
One liner another code:
<
List Comprehensions:
<
for n in range(1, 100):
fb = ''.join([ denom[1] if n % denom[0] == 0 else '' for denom in [(3,'fizz'),(5,'buzz')] ])
print fb if fb else n
</syntaxhighlight>
Another list comprehension:
<
print (', '.join([(x%3<1)*'Fizz'+(x%5<1)*'Buzz' or str(x) for x in range(1,101)]))
</syntaxhighlight>
===Python: List Comprehension (Python 3)===
<
===Python: Lazily===
You can also create a lazy, unbounded sequence by using generator expressions:
<
fizzes = cycle([""] * 2 + ["Fizz"])
Line 8,253 ⟶ 9,512:
# print the first 100
for i in islice(fizzbuzz, 100):
print i</
Or equivalently, in terms of map, and Python 3 libraries:
{{Works with|Python|3.7}}
<
from itertools import count, cycle, islice
Line 8,290 ⟶ 9,549:
if __name__ == '__main__':
main()</
===Python3.8: With walrus operator===
<
===Python: Math tricks===
Numbers ending in 5 or 0 are divisible by 5. Numbers whose digits recursively summed to a single-digit number == 3,6 or 9 are divisible by 3.
<
def numsum(n):
''' The recursive sum of all digits in a number
Line 8,311 ⟶ 9,570:
or n
print(response)
</syntaxhighlight>
===Python3: Super concise: 1 line===
<
print(*((lambda x=x: ''.join(chr(c) for c in (102, 105)) + (2 * chr(122)) + ''.join(chr(c) for c in (98, 117)) + (2 * chr(122)) + '\n' if x % (30 >> 1) == 0 else ''.join(chr(c) for c in (102, 105)) + (2 * chr(122)) + '\n' if x % (6 >> 1) == 0 else ''.join(chr(c) for c in (98, 117)) + (2 * chr(122)) + '\n' if x % (10 >> 1) == 0 else str(x) + '\n')() for x in range(1, 101)))
</syntaxhighlight>
=={{header|
q is the query language for '''kdb+'''.
<syntaxhighlight lang="q">
{(`$string x)^`fizzbuzz`buzz`fizz`(x mod\:15 5 3)?'0}</syntaxhighlight>
Usage:
<syntaxhighlight lang="q">
q)/ Fizzbuzz
q)fb:{(`$string x)^`fizzbuzz`buzz`fizz`(x mod\:15 5 3)?'0}
q)fb 1+til 20
`1`2`fizz`4`buzz`fizz`7`8`fizz`buzz`11`fizz`13`14`fizzbuzz`16`17`fizz`19`buzz</syntaxhighlight>
https://https://q201.org/apply-fizzbuzz//<br>
https://code.kx.com/q/ref/mod/<br>
https://code.kx.com/q/ref/fill
Explanation:
<syntaxhighlight lang="q">
q)show x:1+til 20
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
q)x mod\:15 5 3
1 1 1
2 2 2
3 3 0
4 4 1
5 0 2
6 1 0
..
q)(x mod\:15 5 3)?'0
3 3 2 3 1 2 3 3 2 1 3 2 3 3 0 3 3 2 3 1
q)`fizzbuzz`buzz`fizz`(x mod\:15 5 3)?'0 / substitutions
```fizz``buzz`fizz```fizz`buzz``fizz```fizzbuzz```fizz``buzz
q)`$string x / numbers => symbols
`1`2`3`4`5`6`7`8`9`10`11`12`13`14`15`16`17`18`19`20
q)(`$string x)^`fizzbuzz`buzz`fizz`(x mod\:15 5 3)?'0 / replace nulls with numbers
`1`2`fizz`4`buzz`fizz`7`8`fizz`buzz`11`fizz`13`14`fizzbuzz`16`17`fizz`19`buzz</syntaxhighlight>
=={{header|QB64}}==
<
If n Mod 15 = 0 Then
Print "FizzBuzz"
Line 8,337 ⟶ 9,628:
Print n
End If
Next</
=={{header|Quackery}}==
<
over 3
over 5 mod not
if [ say "buzz" drop
iff echo
sp ]
</syntaxhighlight>
=={{header|R}}==
<
xx[x %% 3 == 0] <- "Fizz"
xx[x %% 5 == 0] <- "Buzz"
xx[x %% 15 == 0] <- "FizzBuzz"
xx</
Or, without directly checking for divisibility by 15:
<
x <- 1:100
xx[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:
<
cat(ifelse(x == "", 1:100, x), sep = "\n")</
Or, for an abuse of the recycling rules that could be generalised:
<
cat(ifelse(x == "", 1:100, x), sep = "\n")</
Or, with a more straightforward use of ifelse:
<
ifelse(x %% 15 == 0, 'FizzBuzz',
ifelse(x %% 5 == 0, 'Buzz',
ifelse(x %% 3 == 0, 'Fizz', x)))</
Or, adapting from [https://rosettacode.org/wiki/General_FizzBuzz#Names_solution General FizzBuzz#Names solution]:
<
for(i in 1:100)
{
isFactor <- i %% namedNums == 0
print(if(any(isFactor)) paste0(names(namedNums)[isFactor], collapse = "") else i)
}</
=={{header|Racket}}==
<
(for ([n (in-range 1 101)])
Line 8,402 ⟶ 9,686:
[3 "fizz"]
[5 "buzz"]
[_ n])))</
=={{header|Raku}}==
Line 8,408 ⟶ 9,692:
{{works with|Rakudo Star|2015-09-10}}
Most straightforwardly:
<syntaxhighlight lang="raku"
when $_ %% (3 & 5) { say 'FizzBuzz'; }
when $_ %% 3 { say 'Fizz'; }
when $_ %% 5 { say 'Buzz'; }
default { .say; }
}</
Or abusing multi subs:
<syntaxhighlight lang="raku"
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:
<syntaxhighlight lang="raku"
Concisely (readable):
<syntaxhighlight lang="raku"
Shortest FizzBuzz to date:
<syntaxhighlight lang="raku"
And here's an implementation that never checks for divisibility:
<syntaxhighlight lang="raku"
(
(flat ('' xx 2, 'Fizz') xx *)
Line 8,434 ⟶ 9,718:
)
Z||
1 .. 100;</
=={{header|RapidQ}}==
The [[#BASIC|BASIC]] solutions work with RapidQ, too.
However, here is a bit more esoteric solution using the IIF() function.
<
t$ = IIF(i MOD 3 = 0, "Fizz", "") + IIF(i MOD 5 = 0, "Buzz", "")
PRINT IIF(LEN(t$), t$, i)
NEXT i</
=={{header|Rascal}}==
<
public void fizzbuzz() {
Line 8,452 ⟶ 9,736:
println((fb == "") ?"<n>" : fb);
}
}</
=={{header|Raven}}==
<
''
n 3 mod 0 = if 'Fizz' cat
n 5 mod 0 = if 'Buzz' cat
dup empty if drop n
say</
=={{header|REALbasic}}==
Line 8,466 ⟶ 9,750:
=={{header|ReasonML}}==
<
let fizzbuzz i =>
switch (i mod 3, i mod 5) {
Line 8,478 ⟶ 9,762:
print_endline (fizzbuzz i)
};
</syntaxhighlight>
=={{header|REBOL}}==
An implementation that concatenates strings and includes a proper code header (title, date, etc.)
<
Title: "FizzBuzz"
URL: http://rosettacode.org/wiki/FizzBuzz
Line 8,499 ⟶ 9,783:
]
print x
]</
Here is an example by Nick Antonaccio.
<
print switch/default 0 compose [
(mod i 15) ["fizzbuzz"]
Line 8,507 ⟶ 9,791:
(mod i 5) ["buzz"]
][i]
]</
And a minimized version:
<
The following is presented as a curiosity only, not as an example of good coding practice:
<
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]</
=={{header|Red}}==
<
repeat i 100 [
Line 8,528 ⟶ 9,812:
true [i]
]
]</
=={{header|Refal}}==
<syntaxhighlight lang="refal">$ENTRY Go {
= <FizzBuzz 1>;
};
FizzBuzz {
101 = ;
s.N = <Prout <Item s.N>>
<FizzBuzz <+ 1 s.N>>;
};
Item {
s.N, <Mod s.N 15>: 0 = FizzBuzz;
s.N, <Mod s.N 5>: 0 = Buzz;
s.N, <Mod s.N 3>: 0 = Fizz;
s.N = s.N;
};</syntaxhighlight>
=={{header|Retro}}==
This is a port of some [http://weblog.raganwald.com/2007/01/dont-overthink-fizzbuzz.html Forth code].
<
: buzz? ( s-f ) 5 mod 0 = ;
: num? ( s-f ) dup fizz? swap buzz? or 0 = ;
Line 8,539 ⟶ 9,841:
: ?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:
<
: <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 ;</
=={{header|REXX}}==
Line 8,552 ⟶ 9,854:
This version's program logic closely mirrors the problem statement:
===three IF-THEN===
<
/*╔═══════════════════════════════════╗*/
do j=1 to 100; z= j /*║ ║*/
Line 8,559 ⟶ 9,861:
if j//(3*5)==0 then z= 'FizzBuzz' /*║ ║*/
say right(z, 8) /*╚═══════════════════════════════════╝*/
end /*j*/ /*stick a fork in it, we're all done. */</
'''output'''
<pre style="height:40ex">
Line 8,667 ⟶ 9,969:
This version is a different form, but essentially identical to the '''IF-THEN''' (above),
<br>but doesn't require the use of a temporary variable to hold/contain the output.
<
/*╔═══════════════════════════════════╗*/
do j=1 to 100 /*║ ║*/
Line 8,676 ⟶ 9,978:
otherwise say right(j, 8) /*╚═══════════════════════════════════╝*/
end /*select*/
end /*j*/ /*stick a fork in it, we're all done. */</
'''output''' is identical to the 1<sup>st</sup> REXX version.
===two IF-THEN===
This version lends itself to expansion (such as using '''Jazz''' for multiples of '''7''').
<
do j=1 for 100; _=
Line 8,688 ⟶ 9,990:
/* 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 1<sup>st</sup> REXX version.
==="geek" version===
<
/* [↓] 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 1<sup>st</sup> REXX version. <br><br>
=={{header|Rhovas}}==
Standard FizzBuzz using a pattern matching approach:
* <code>range(1, 100, :incl)</code> creates an inclusion range
* <code>.for {</code> iterates through the range, with the current element being <code>val</code>
* Pattern matching on <code>[val.mod(3), val.mod(5)]</code> is used to check divisibility conditions
** <code>[0, 0]</code>, for instance, matches when <code>val</code>is divisible by both <code>3</code> and <code>5</code>
** <code>else</code> matches all other possibilities, in this case when <code>val</code> is not divisible by <code>3</code> or <code>5</code>
<syntaxhighlight lang="scala">
range(1, 100, :incl).for {
match ([val.mod(3), val.mod(5)]) {
[0, 0]: print("FizzBuzz");
[0, _]: print("Fizz");
[_, 0]: print("Buzz");
else: print(val);
}
};
</syntaxhighlight>
=={{header|Ring}}==
<
for n = 1 to 100
if n % 15 = 0 see "" + n + " = " + "FizzBuzz" + nl loop
but n % 3 = 0 see "" + n + " = " + "Fizz"+ nl
but n % 5 = 0 see "" + n + " = " + "Buzz" + nl
else see "" + n + " = " + n + nl ok
next</syntaxhighlight>
{{out}}
Limited to first 20.
<pre>
1 = 1
2 = 2
3 = Fizz
4 = 4
5 = Buzz
6 = Fizz
7 = 7
8 = 8
9 = Fizz
10 = Buzz
11 = 11
12 = Fizz
13 = 13
14 = 14
15 = FizzBuzz
16 = 16
17 = 17
18 = Fizz
19 = 19
20 = Buzz
</pre>
=={{header|Robotic}}==
<
set "local1" to 1
: "loop"
Line 8,738 ⟶ 10,083:
: "done"
end
</syntaxhighlight>
The '''wait for 10''' function is not really necessary, but it helps to slow down the output.
Line 8,770 ⟶ 10,115:
Whisper my world
=={{header|RPG}}==
<nowiki>**</nowiki>free
dcl-s ix Int(5);
for ix = 1 to 100;
select;
when %rem(ix:15) = 0;
dsply 'FizzBuzz';
when %rem(ix:5) = 0;
dsply 'Buzz';
when %rem(ix:3) = 0;
dsply 'Fizz';
other;
dsply (%char(ix));
endsl;
endfor;
=={{header|RPL}}==
Structured programming:
≪ { } 1 100 '''FOR''' j
'''IF''' j 3 MOD '''THEN''' "" '''ELSE''' "Fizz" '''END'''
'''IF''' j 5 MOD NOT '''THEN''' "Buzz" + '''END'''
'''IF''' DUP SIZE NOT '''THEN''' DROP j '''END'''
+ '''NEXT'''
≫ ''''FIZZB'''' STO
Arithmetic:
≪ { } 1 100 '''FOR''' j
j 3 MOD NOT j 5 MOD NOT → a b
≪ '''IF''' a b + '''THEN''' "FizzBuzz" 5 4 a * - a b 2 * MAX 4 * SUB '''ELSE''' j '''END'''
≫ + '''NEXT'''
≫ ''''FIZZB'''' STO
Data-centric:
≪ "FizzBuzz" { (1,4) (5,8) (1,8) } → fb idx
≪ { } 1 100 '''FOR''' j
'''IF''' j 3 MOD NOT j 5 MOD NOT 2 * + '''THEN''' fb idx LAST GET C→R SUB '''ELSE''' j '''END'''
+ '''NEXT'''
≫ ≫ ''''FIZZB'''' STO
Esoteric one-liner:
≪ ≪ j ROT MOD "" ROT IFTE ≫ → f ≪ { } 1 100 FOR j 3 "Fizz" f EVAL 5 "Buzz" f EVAL + SIZE LAST j IFTE + NEXT ≫ ≫ EVAL
=={{header|Ruby}}==
<
print "Fizz" if a = (n % 3).zero?
print "Buzz" if b = (n % 5).zero?
print n unless (a || b)
puts
end</
A bit more straightforward:
<
puts if (n % 15).zero?
"FizzBuzz"
Line 8,789 ⟶ 10,173:
n
end
end</
Enumerable#Lazy and classes:
Line 8,795 ⟶ 10,179:
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
Line 8,887 ⟶ 10,271:
min(2,b) if b < f and b < fb
min(0,fb) if fb < b and fb < f
end</
An example using string interpolation:
<
v = "#{"Fizz" if n % 3 == 0}#{"Buzz" if n % 5 == 0}"
puts v.empty? ? n : v
end</
Interpolation inspired one-liner:
<
An example using append:
<
r = ''
r << 'Fizz' if n % 3 == 0
Line 8,905 ⟶ 10,289:
r << n.to_s if r.empty?
puts r
end</
Yet another solution:
<syntaxhighlight lang="text">1.upto(100) { |i| puts "#{[:Fizz][i%3]}#{[:Buzz][i%5]}"[/.+/] || i }</
Yet another solution:
<
Used Enumerable#cycle:
<
b = [nil, nil, nil, nil, :Buzz].cycle
(1..100).each do |i|
puts "#{f.next}#{b.next}"[/.+/] || i
end</
After beforehand preparing the Array which put the number from 1 to 100, it processes.
<
{Fizz:3, Buzz:5, FizzBuzz:15}.each{|k,n| n.step(100,n){|i|seq[i]=k}}
puts seq.drop(1)</
Monkeypatch example:
<
def fizzbuzz
v = "#{"Fizz" if self % 3 == 0}#{"Buzz" if self % 5 == 0}"
Line 8,933 ⟶ 10,317:
end
puts *(1..100).map(&:fizzbuzz)</
Without mutable variables or inline printing.
<
(i%15).zero? and next "FizzBuzz"
(i%3).zero? and next "Fizz"
Line 8,943 ⟶ 10,327:
end
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?]
Line 8,960 ⟶ 10,344:
end
end
</syntaxhighlight>
=={{header|Ruby with RSpec}}==
Line 8,968 ⟶ 10,352:
Your spec/fizzbuzz_spec.rb file should like this:
<
require 'fizzbuzz'
Line 9,009 ⟶ 10,393:
end
end
</
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)
Line 9,037 ⟶ 10,421:
end
</syntaxhighlight>
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 [https://www.youtube.com/watch?v=CHTep2zQVAc&feature=youtu.be FizzBuzz implementation using Ruby & RSpec].
Line 9,047 ⟶ 10,431:
Basic example with a for loop and match:
<
for i in 1..=100 {
match (i % 3, i % 5) {
Line 9,056 ⟶ 10,440:
}
}
}</
Using an iterator and immutable data:
<
fn main() {
Line 9,072 ⟶ 10,456:
.for_each(|n| println!("{:?}", n));
}
</syntaxhighlight>
A folding iterator version, buffered with a single string allocation, by making use of expressions the <code>write!</code> macro.
<
fn fizzbuzz() -> String {
Line 9,093 ⟶ 10,477:
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.
<
#![feature(asm, lang_items, libc, no_std, start)]
Line 9,132 ⟶ 10,516:
#[lang = "eh_personality"] extern fn eh_personality() {}
#[lang = "panic_fmt"] extern fn panic_fmt() {}</
=={{header|Salmon}}==
<
((x % 15 == 0) ? "FizzBuzz" :
((x % 3 == 0) ? "Fizz" :
((x % 5 == 0) ? "Buzz" : x)))!;</
or
<
{
if (x % 15 == 0)
Line 9,150 ⟶ 10,534:
else
x!;
};</
=={{header|SAS}}==
<
do i=1 to 100;
if mod(i,15)=0 then put "FizzBuzz";
Line 9,160 ⟶ 10,544:
else put i;
end;
run;</
=={{header|Sather}}==
<
main is
loop i ::= 1.upto!(100);
Line 9,176 ⟶ 10,560:
end;
end;
end;</
=={{header|Scala}}==
Line 9,182 ⟶ 10,566:
===Idiomatic scala code===
<
1 to 100 foreach { n =>
println((n % 3, n % 5) match {
Line 9,191 ⟶ 10,575:
})
}
}</
===Geeky over-generalized solution ☺===
<
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))))
Line 9,200 ⟶ 10,584:
def fizzbuzz = replaceMultiples(_: Int, 3 -> "Fizz", 5 -> "Buzz") fold(_.toString, identity)
1 to 100 map fizzbuzz foreach println</
===By a two-liners geek===
<
for (i <- 1 to 100) println(f(i, 15, "FizzBuzz", f(i, 3, "Fizz", f(i, 5, "Buzz", i.toString))))</
===One-liner geek===
<
===Functional Scala===
<
if (n % 15 == 0) "FizzBuzz"
else if (n % 3 == 0) "Fizz"
Line 9,216 ⟶ 10,600:
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.
<
(n % 3, n % 5) match // optional semantic indentation; no braces
case (0, 0) => "FizzBuzz"
Line 9,233 ⟶ 10,617:
@main def run(): Unit = // @main for main method; can take custom args
fizzBuzz.take(100).foreach(println)</
=={{header|Scheme}}==
<
((> i 100))
(display
Line 9,243 ⟶ 10,627:
((= 0 (modulo i 5)) "Buzz")
(else i)))
(newline))</
Using a recursive procedure.
<
(println
(cond (( = (modulo x 15) 0 ) "FizzBuzz")
Line 9,256 ⟶ 10,640:
(if (< x y) (fizzbuzz (+ x 1) y)))
(fizzbuzz 1 100)</
Approach with maps and filters, easier to change, less readable
than the previous.
<
(let ([words '((3 . "Fizz")
(5 . "Buzz"))])
Line 9,269 ⟶ 10,653:
(fizzbuzz 15)
</syntaxhighlight>
=={{header|Sed}}==
<
# doesn't work if there's no input
# initialize counters (0 = empty) and value
Line 9,311 ⟶ 10,695:
# loop until value = 100
/100/q
b loop</
Using <tt>seq</tt>:
<
seq 100 | sed '/.*[05]$/s//Buzz/;n;s//Buzz/;n;s//Buzz/;s/^[0-9]*/Fizz/'
</syntaxhighlight>
=== GNU sed ===
Line 9,323 ⟶ 10,707:
Using <tt>seq</tt>:
<
seq 100 | sed '0~3 s/.*/Fizz/; 0~5 s/[0-9]*$/Buzz/'
</syntaxhighlight>
Using <tt>yes</tt>:
<
yes | sed -n '0~3s/y/Fizz/;0~5s/y*$/Buzz/;tx;=;b;:x;p;100q'
</syntaxhighlight>
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/\c@/\n/'
</syntaxhighlight>
Second invocation of ''sed'' translates null characters to newlines. The same could be achieved with <tt>tr \\0 \\n</tt>
=={{header|Seed7}}==
<
const proc: main is func
Line 9,356 ⟶ 10,740:
end if;
end for;
end func;</
=={{header|SenseTalk}}==
<
put "" into output
if the counter is a multiple of 3 then
Line 9,371 ⟶ 10,755:
end if
put output
end repeat</
=={{header|SETL}}==
<syntaxhighlight lang="setl">program fizzbuzz;
loop for n in [1..100] do
print(fizzbuzz(n));
end loop;
proc fizzbuzz(n);
divs := [[3, "Fizz"], [5, "Buzz"]];
return +/[w : [d,w] in divs | n mod d=0] ? str n;
end proc;
end program;</syntaxhighlight>
=={{header|SequenceL}}==
<
import <Utilities/Sequence.sl>;
Line 9,390 ⟶ 10,786:
foreach i within 1 ... 100;
in
delimit(result, '\n');</
=={{header|Shale}}==
<
string library
Line 9,407 ⟶ 10,803:
r "" equals string::() { i } { r } if i "%3d: %p\n" printf
i++
} while</
=={{header|Shen}}==
<
101 -> (nl)
N -> (let divisible-by? (/. A B (integer? (/ A B)))
Line 9,423 ⟶ 10,819:
(fizzbuzz (+ N 1))))))
(fizzbuzz 1)</
=== Alternative showing off other features like prolog integration and guards ===
<
0 <-- (is _ (output "Fizz"));
N <-- (when (> N 0)) (is N1 (- N 3)) (fizz N1);
Line 9,455 ⟶ 10,851:
(fizzbuzz 1 100)
</syntaxhighlight>
=={{header|Sidef}}==
Structured:
<
if (i %% 3) {
print "Fizz"
Line 9,467 ⟶ 10,863:
elsif (i %% 5) { say "Buzz" }
else { say i }
}
Declarative:
<
func fizzbuzz({ _ %% 5 }) { "Buzz" }
func fizzbuzz({ _ %% 3 }) { "Fizz" }
func fizzbuzz( n ) { n }
for n in (1..100) { say fizzbuzz(n) }</
One-liner:
<
=={{header|Simula}}==
<
integer i;
for i := 1 step 1 until 100 do
Line 9,495 ⟶ 10,891:
outimage
end;
end</
=={{header|SkookumScript}}==
Answer by printing out one of the 4 alternatives:
<
1.to 100
[
Line 9,508 ⟶ 10,904:
else [idx])
]
</syntaxhighlight>
Answer by building up a string:
<
1.to 100
[
Line 9,519 ⟶ 10,915:
println(if str.empty? [idx] else [str])
]
</syntaxhighlight>
Or doing initial bind in one step:
<
1.to 100
[
Line 9,529 ⟶ 10,925:
println(if str.empty? [idx] else [str])
]
</syntaxhighlight>
=={{header|Slate}}==
<
[
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]</
=={{header|Slope}}==
<syntaxhighlight lang="scheme">
(define fizz-buzz
(lambda (x)
(define ret "")
(if (zero? (% x 3))(set! ret (append ret "fizz")))
(if (zero? (% x 5))(set! ret (append ret "buzz")))
(if (equal? ret "") (set! ret (append ret x)))
ret))
(apply display-lines (list-join (map fizz-buzz (range 100 1))))
</syntaxhighlight>
=={{header|Small}}==
See [[FizzBuzz/EsoLang]]
=={{header|SmallBASIC}}==
See [[FizzBuzz/Basic]]
=={{header|Smalltalk}}==
Since only GNU Smalltalk supports file-based programming, we'll be using its syntax.
<
fizzbuzz [
| fb |
Line 9,552 ⟶ 10,963:
]
]
1 to: 100 do: [ :i | i fizzbuzz displayNl ]</
A Squeak/Pharo example using the Transcript window:
<
[:n |
((n \\ 3)*(n \\ 5)) isZero
Line 9,562 ⟶ 10,973:
(n \\ 5) isZero
ifTrue: [Transcript show: 'Buzz'].
Transcript cr.]</
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.
<
with: #(true false)->'Fizz'
with: #(false true)->'Buzz'.
Line 9,571 ⟶ 10,982:
[ :i | Transcript show:
(fizzbuzz at: {i isDivisibleBy: 3. i isDivisibleBy: 5}
ifAbsent: [ i ]); cr]</
Smalltalk does not have a case-select construct, but a similar effect can be attained using a collection and the #includes: method:
<
r := n rem: 15.
Transcript show: (r isZero
Line 9,582 ⟶ 10,993:
ifTrue:['buzz']
ifFalse:[n]]]);
cr].</
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):
<
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].</
The approach building a dynamic string can be done as well:
<
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].</
=={{header|SNOBOL4}}==
Merely posting a solution by Daniel Lyons
<
LOOP FIZZBUZZ = ""
EQ(REMDR(I, 3), 0) :F(TRY_5)
Line 9,609 ⟶ 11,020:
I = I + 1
LE(I, 100) :S(LOOP)
END</
=={{header|SNUSP}}==
See [[FizzBuzz/EsoLang]]
=={{header|SparForte}}==
As a structured script.
<syntaxhighlight lang="ada">#!/usr/local/bin/spar
pragma annotate( summary, "fizzbuzz" );
pragma annotate( description, "Write a program that prints the numbers from 1 to 100. But for multiples of" );
pragma annotate( description, "three print 'Fizz' instead of the number and for the multiples of five print" );
pragma annotate( description, "'Buzz'. For numbers which are multiples of both three and five print" );
pragma annotate( description, "'FizzBuzz'" );
pragma annotate( see_also, "http://rosettacode.org/wiki/FizzBuzz" );
pragma annotate( author, "Ken O. Burtch" );
pragma license( unrestricted );
pragma restriction( no_external_commands );
procedure fizzbuzz is
begin
for i in 1..100 loop
if i mod 15 = 0 then
? "FizzBuzz";
elsif i mod 5 = 0 then
? "Buzz";
elsif i mod 3 = 0 then
? "Fizz";
else
? i;
end if;
end loop;
end fizzbuzz;</syntaxhighlight>
=={{header|SQL}}==
{{libheader|SQL}}
===Oracle SQL===
<
WHEN MOD(level,15)=0 THEN 'FizzBuzz'
WHEN MOD(level,3)=0 THEN 'Fizz'
Line 9,624 ⟶ 11,064:
END FizzBuzz
FROM dual
CONNECT BY LEVEL <= 100;</
Or using Oracle's DECODE and NVL:
<
FROM dual
CONNECT BY level<=100;</
===PostgreSQL specific===
<
FROM
(SELECT i,
Line 9,641 ⟶ 11,081:
END AS fizzbuzz
FROM generate_series(1,100) AS i) AS fb
WHERE fizzbuzz IS NOT NULL;</
Using Generate_Series and tables only:
<
(SELECT GENERATE_SERIES AS FULL_SERIES, TO_CHAR(GENERATE_SERIES,'99') AS OUTPUT
FROM GENERATE_SERIES(1,100)) F LEFT JOIN
Line 9,650 ⟶ 11,090:
FIZZ.FIZZ_SERIES = F.FULL_SERIES LEFT JOIN
(SELECT TEXT 'Buzz' AS BUZZ, GENERATE_SERIES AS BUZZ_SERIES FROM GENERATE_SERIES(0,100,5)) BUZZ ON
BUZZ.BUZZ_SERIES = F.FULL_SERIES;</
===Recursive Common Table Expressions (MSSQL 2005+)===
<
SELECT 1, CONVERT(nvarchar, 1) UNION ALL
SELECT
Line 9,667 ⟶ 11,107:
SELECT n, fizzbuzz FROM nums
ORDER BY n ASC
OPTION ( MAXRECURSION 100 )</
===SQL Anywhere specific - minimalist===
<syntaxhighlight lang="sql">SELECT
isnull(if row_num % 3 = 0 then 'Fizz' endif + if row_num % 5 = 0 then 'Buzz' endif, str(row_num))
FROM
sa_rowgenerator(1,100)</syntaxhighlight>
===Generic SQL using a join===
This should work in most RDBMSs, but you may need to change <tt>MOD(i,divisor)</tt> to <tt>i % divisor</tt>.
<
CREATE TABLE numbers(i INTEGER);
INSERT INTO numbers VALUES(1);
Line 9,693 ⟶ 11,139:
-- Tidy up
DROP TABLE fizzbuzz;
DROP TABLE numbers;</
=={{header|Squirrel}}==
<
for (local i = 1; i <= n; i += 1) {
if (i % 15 == 0)
Line 9,709 ⟶ 11,155:
}
}
Fizzbuzz(100);</
=={{header|Stata}}==
<
args n
forvalues i = 1/`n' {
Line 9,728 ⟶ 11,174:
}
}
end</
=={{header|Swahili}}==
<
shughuli fizzBuzz() {
kwa i = 1 mpaka 100 {
Line 9,745 ⟶ 11,191:
}
}
</syntaxhighlight>
=={{header|Swift}}==
=== using a switch statement ===
<
switch (i % 3, i % 5) {
case (0, 0):
Line 9,760 ⟶ 11,206:
print(i)
}
}</
=== using two if statements and an Optional ===
<
var s:String?
if i%3==0{s="Fizz"}
if i%5==0{s=(s ?? "")+"Buzz"}
print(s ?? i)
}</
=== using a precomputed cycle ===
<syntaxhighlight lang="swift">
import Foundation
let formats: [String] = [
"%d",
"%d",
"fizz",
"%d",
"buzz",
"fizz",
"%d",
"%d",
"fizz",
"buzz",
"%d",
"fizz",
"%d",
"%d",
"fizzbuzz",
]
var count = 0
var index = 0
while count < 100 {
count += 1
print(String(format: formats[index], count))
index += 1
index %= 15
}
</syntaxhighlight>
=={{header|Symstatic}}==
<syntaxhighlight lang="symstatic">let fizzBuzz := n -> (
let fb(0, 0) := "fizzbuzz",
let fb(0, _) := "fizz",
let fb(_, 0) := "buzz",
let fb(_, _) := n,
fb(n % 3, n % 5),
)
for i in 1..101: println(fizzBuzz(i))
</syntaxhighlight>
=={{header|Symsyn}}==
<
| FizzBuzz
Line 9,793 ⟶ 11,283:
goif
endif
</syntaxhighlight>
=={{header|Tailspin}}==
<
templates fizz
$ mod 3 -> #
Line 9,809 ⟶ 11,299:
[ 1..100 -> '$->fizz;$->buzz;' ] -> \[i](when <=''> do $i ! otherwise $ !\)... -> '$;
' -> !OUT::write
</syntaxhighlight>
=={{header|tbas}}==
See [[FizzBuzz/Basic]]
=={{header|Tcl}}==
<
for {set i 1} {$i <= $n} {incr i} {
set ans ""
Line 9,820 ⟶ 11,313:
}
}
fizzbuzz 100</
The following example shows Tcl's substitution mechanism that allows to concatenate the results of two successive commands into a string:
<
set fb [if {$i % 3 == 0} {list Fizz}][if {$i % 5 == 0} {list Buzz}]
if {$fb ne ""} {puts $fb} {puts $i}
}</
This version uses list rotation, so avoiding an explicit mod operation:
<
foreach i {5 10} {lset f $i "Buzz"};lset f 0 "FizzBuzz"
for {set i 1} {$i <= 100} {incr i} {
puts [subst [lindex [set f [list {*}[lassign $f ff] $ff]] 0]]
}</
=={{header|TI SR-56}}==
{| class="wikitable"
|+ Texas Instruments SR-56 Program Listing for "Fizzbuzz"
|-
! Display !! Key !! Display !! Key !! Display !! Key !! Display !! Key
|-
| 00 22 || GTO || 25 64 || x || 50 03 || 3 || 75 ||
|-
| 01 03 || 3 || 26 52 || ( || 51 34 || RCL || 76 ||
|-
| 02 07 || 7 || 27 52 || ( || 52 01 || 1 || 77 ||
|-
| 03 53 || ) || 28 34 || RCL || 53 59 || *pause || 78 ||
|-
| 04 12 || INV || 29 01 || 1 || 54 22 || GTO || 79 ||
|-
| 05 29 || *Int || 30 54 || / || 55 03 || 3 || 80 ||
|-
| 06 56 || *CP || 31 05 || 5 || 56 08 || 8 || 81 ||
|-
| 07 12 || INV || 32 57 || subr || 57 || || 82 ||
|-
| 08 37 || *x=t || 33 00 || 0 || 58 || || 83 ||
|-
| 09 01 || 1 || 34 03 || 3 || 59 || || 84 ||
|-
| 10 03 || 3 || 35 94 || = || 60 || || 85 ||
|-
| 11 01 || 1 || 36 58 || rtn || 61 || || 86 ||
|-
| 12 84 || + || 37 38 || *CMs || 62 || || 87 ||
|-
| 13 00 || 0 || 38 01 || 1 || 63 || || 88 ||
|-
| 14 53 || ) || 39 35 || SUM || 64 || || 89 ||
|-
| 15 58 || rtn || 40 02 || 2 || 65 || || 90 ||
|-
| 16 33 || STO || 41 34 || RCL || 66 || || 91 ||
|-
| 17 01 || 1 || 42 02 || 2 || 67 || || 92 ||
|-
| 18 54 || / || 43 57 || subr || 68 || || 93 ||
|-
| 19 03 || 3 || 44 01 || 1 || 69 || || 94 ||
|-
| 20 57 || subr || 45 06 || 6 || 70 || || 95 ||
|-
| 21 00 || 0 || 46 93 || +/- || 71 || || 96 ||
|-
| 22 03 || 3 || 47 12 || INV || 72 || || 97 ||
|-
| 23 84 || + || 48 47 || *x>=t || 73 || || 98 ||
|-
| 24 02 || 2 || 49 05 || 5 || 74 || || 99 ||
|}
Asterisk denotes 2nd function key.
{| class="wikitable"
|+ Register allocation
|-
| 0: Unused || 1: Argument || 2: Number || 3: Unused || 4: Unused
|-
| 5: Unused || 6: Unused || 7: Unused || 8: Unused || 9: Unused
|}
Annotated listing:
<syntaxhighlight lang="text">
// Address 00: Entry point
GTO 3 7 // Jump to the main program
// Address 03: Subroutine
// Takes a pending division such as ((12/5 and evaluates whether it
// is evenly divisible.
// Result 1: evenly divisible, 0: not divisible
) // Complete the pending division
INV *Int // Take the fractional part
*CP // RegT := 0
INV *x=t 1 3 // If fractional part is zero, don't increment
1 + // Start a pending increment of the return value
0 ) rtn // Return the return value
// Address 16: Subroutine
// Takes a number and evaluates whether it is divisible by 3 and 5.
// Result: 0=indivisible, 1=fizz, 2=buzz, 3=fizzbuzz
STO 1 // Save subroutine argument
/ 3 subr 0 3 // 1 if fizz else 0
+ 2 x // Buzz is worth 2x as much as Fizz
( ( RCL 1 / 5 subr 0 3 // 1 if buzz else 0
= // Finish the pending + and x
rtn // Return result
// Address 37: Main program
*CMs // Zero out registers
1 SUM 2 // Number += 1
RCL 2 // Retrieve Number
subr 1 6 // Evaluate whether it is divisible by 3 and 5
+/- // Negate (0=indiv., -1=fizz, -2=buzz, -3=fizzbuzz)
INV *x>=t 5 3 // If negative, skip the next line.
RCL 1 // Retrieve number instead of zero.
*pause // Flash the number on the display
GTO 3 8 // Loop
</syntaxhighlight>
'''Usage:'''
Press RST R/S to start the program. Increasing numbers will flash on the screen. Positive numbers represent themselves; -1 means fizz, -2 buzz and -3 fizzbuzz. About 25 numbers are calculated per minute.
=={{header|TI-83 BASIC}}==
Line 9,838 ⟶ 11,445:
=={{header|TI-83 Hex Assembly}}==
See [[FizzBuzz/Assembly]]
=={{header|TI-99/4a TI BASIC / Extended BASIC}}==
See [[FizzBuzz/Basic]]
=={{Header|Tiny BASIC}}==
See [[FizzBuzz/Basic]]
=={{header|TransFORTH}}==
<
101 1 DO
I 15 MOD 0 = IF
Line 9,849 ⟶ 11,462:
PRINT " BUZZ "
ELSE I . THEN THEN THEN
CR LOOP ;</
=={{header|True BASIC}}==
Line 9,855 ⟶ 11,468:
=={{header|Turing}}==
<
if i mod 15 = 0 then
put "Fizzbuzz"
Line 9,865 ⟶ 11,478:
put i
end if
end for</
=={{header|TUSCRIPT}}==
<
LOOP n=1,100
mod=MOD (n,15)
Line 9,881 ⟶ 11,494:
PRINT n
ENDSELECT
ENDLOOP</
=={{header|TXR}}==
<
=={{header|UNIX Shell}}==
This solution should work with any Bourne-compatible shell: <!-- http://ideone.com/usJXGo -->
<
while expr $i '<=' 100 >/dev/null; do
w=false
Line 9,895 ⟶ 11,508:
if $w; then echo; else echo $i; fi
i=`expr $i + 1`
done</
===Versions for specific shells===
Line 9,903 ⟶ 11,516:
and it should work with every POSIX shell.
<!-- http://ideone.com/5yZmOz -->
<
while [ 100 -ge n ]; do
if [ $((n % 15)) -eq 0 ]; then
Line 9,915 ⟶ 11,528:
fi
n=$((n + 1))
done</
The next solution requires the <code>(( ))</code> command from the [[Korn Shell]].
{{works with|pdksh|5.2.14}}
<
until ((NUM == 101)) ; do
if ((NUM % 15 == 0)) ; then
Line 9,931 ⟶ 11,544:
fi
((NUM = NUM + 1))
done</
A version using concatenation:
{{works with|bash|3}}
<
do
fb=''
Line 9,941 ⟶ 11,554:
[ $(( n % 5 )) -eq 0 ] && fb="${fb}Buzz"
[ -n "${fb}" ] && echo "${fb}" || echo "$n"
done</
A version using some of the insane overkill of Bash 4:
{{works with|bash|4}}
<
local Fizz=3 Buzz=5
[ $(( $2 % $1 )) -eq 0 ] && echo -n $1 && [ ${!1} -eq 3 ]
Line 9,954 ⟶ 11,567:
Fizz $i && ! Buzz $i || echo -n $i
echo
done</
Bash one-liner: <!-- http://ideone.com/xMEGFK -->
<
==={{header|C Shell}}===
<
while ( $n <= 100 )
if ($n % 15 == 0) then
Line 9,972 ⟶ 11,585:
endif
@ n += 1
end</
=={{header|Uiua}}==
<syntaxhighlight lang="Uiua">
⟨&p|&p"Fizz"|&p"Buzz"|&p"Fizzbuzz"⟩°⋯⍉=0⊞◿3_5.+1⇡100
</syntaxhighlight>
=={{header|Ursa}}==
<
# fizzbuzz
#
Line 9,990 ⟶ 11,608:
end if
out endl console
end for</
=={{header|Ursala}}==
<
#import nat
Line 10,000 ⟶ 11,618:
#show+
main = fizzbuzz*t iota 101</
=={{header|V}}==
<
1 [>=] [
[[15 % zero?] ['fizzbuzz' puts]
Line 10,011 ⟶ 11,629:
] when succ
] while].
|100 fizzbuzz</
===Second try===
Line 10,017 ⟶ 11,635:
define a command that will generate a sequence
<
create a quote that will return a quote that returns a quote if its argument is an integer (A HOF)
<
Create a quote that will make sure that the above quote is applied correctly if given (Number Function)
as arguments.
<
And apply it
<
[15 [pop 'fizzbuzz' puts]]
[5 [pop 'buzz' puts]]
[3 [pop 'fizz' puts]]
[1 [puts]]] [func dup] step
[i true] map pop</
the first one is much better :)
=={{header|Vala}}==
<
for (int i = 1; i <= 100; i++) {
if (i % 3 == 0) stdout.printf("Fizz\n");
Line 10,042 ⟶ 11,660:
}
return 0;;
}</
=={{header|Vale}}==
{{works with|Vale|0.2.0}}
<syntaxhighlight lang="vale">
import stdlib.*;
exported func main(){
fizzBuzz(1, 100);
}
func fizzBuzz(i int, stop int) {
result = if i.mod(3) == 0 {
"Fizz" } else { ""
} + if i.mod(5) == 0 {
"Buzz" } else { ""
};
println(if result == "" { i.str() } else { result });
if i < stop {
return fizzBuzz(i + 1, stop);
}
}
</syntaxhighlight>
=={{header|VAX Assembly}}==
<
00000008 0000 2 msg: .blkb len ;output buffer
0000000C 0008 3 desc: .blkl 1 ;descriptor lenght field
Line 10,087 ⟶ 11,729:
9F 52 00000064 8F F3 007C 41 AOBLEQ #100,r2,loop ;limit.rl, index.ml
04 0084 42 ret
0085 43 .end start</
=={{header|VBA}}==
<syntaxhighlight lang="vb">
Option Explicit
Line 10,109 ⟶ 11,751:
Next
Debug.Print Join(Tb, vbCrLf)
End Sub</
As an alternative, testing each number only once:
<syntaxhighlight lang="vb">
Sub FizzBuzz()
Dim i As Integer
Line 10,122 ⟶ 11,764:
Debug.Print Join(T, ", ") & ", Buzz"
End Sub
</syntaxhighlight>
=={{header|VBScript}}==
{{works with|Windows Script Host|*}}
<
If i Mod 15 = 0 Then
WScript.Echo "FizzBuzz"
Line 10,136 ⟶ 11,778:
WScript.Echo i
End If
Next</
=====An Alternative=====
{{works with|Windows Script Host|*}}
<
For i = 1 To 100
If i Mod 3 = 0 Then .Write "Fizz"
Line 10,146 ⟶ 11,788:
If .Column = 1 Then .WriteLine i Else .WriteLine ""
Next
End With</
=={{header|Verbexx}}==
<
{
t3 = (i % 3 == 0);
Line 10,159 ⟶ 11,801:
else: { i }
);
};</
=={{header|Verilog}}==
<syntaxhighlight lang="verilog">
module main;
integer number;
Line 10,182 ⟶ 11,824:
end
endmodule
</syntaxhighlight>
=={{header|VHDL}}==
<
end entity fizzbuzz;
Line 10,214 ⟶ 11,856:
end process p_fizz;
end architecture beh;</
=={{header|Vim Script}}==
<
if i % 15 == 0
echo "FizzBuzz"
Line 10,227 ⟶ 11,869:
echo i
endif
endfor</
=={{header|Visual Basic .NET}}==
Line 10,233 ⟶ 11,875:
=={{header|Visual Prolog}}==
<syntaxhighlight lang="text">
implement main
open core, console
Line 10,256 ⟶ 11,898:
goal
console::runUtf8(main::run).
</syntaxhighlight>
=={{header|V (Vlang)}}==
Updated for V (Vlang) version 0.2.2
<
fizz = Tuple{true, false}
buzz = Tuple{false, true}
Line 10,289 ⟶ 11,931:
fizzbuzz(15)
}
</syntaxhighlight>
{{out}}
<pre>1
Line 10,310 ⟶ 11,952:
Basic example with a for loop and match:
<syntaxhighlight lang="go">
fn main() {
mut i := 1
Line 10,323 ⟶ 11,965:
}
}
</syntaxhighlight>
Another basic example using the ubiquitous if/else (if) statement:
<syntaxhighlight lang="go">
fn main() {
for i in 1..100 {
Line 10,341 ⟶ 11,983:
}
}
</syntaxhighlight>
{{out}}
<pre style="height:40ex">
Line 10,447 ⟶ 12,089:
=={{header|VTL-2}}==
<
20 #=30
30 #=N/3*0+%=0*110
Line 10,461 ⟶ 12,103:
130 ?="Buzz";
140 #=!
180 #=70</
=={{header|Wart}}==
<
prn (if (divides i 15)
"FizzBuzz"
Line 10,472 ⟶ 12,114:
"Buzz"
:else
i)</
=={{header|WDTE}}==
<
let s => import 'stream';
Line 10,487 ⟶ 12,129:
} -- io.writeln io.stdout;
s.range 1 101 -> s.map fizzbuzz -> s.drain;</
=={{header|Whitespace}}==
Line 10,493 ⟶ 12,135:
=={{header|Wortel}}==
<
=={{header|Wren}}==
<
if (i % 15 == 0) {
System.print("FizzBuzz")
Line 10,506 ⟶ 12,148:
System.print(i)
}
}</
{{out}}
Line 10,613 ⟶ 12,255:
=={{header|X86 Assembly}}==
<
; x86_64 linux nasm
Line 10,718 ⟶ 12,360:
syscall
ret
</syntaxhighlight>
=={{header|XBasic}}==
See [[FizzBuzz/Basic]]
=={{header|XLISP}}==
<
(defun fizzb (x y)
(display (cond
Line 10,733 ⟶ 12,378:
(fizzb 1 100))
(fizzbuzz)</
=={{header|XMIDAS}}==
<
loop 100 count
calc/quiet three ^count 3 modulo
Line 10,750 ⟶ 12,395:
endif
endloop
endmacro</
=={{header|Xojo}}==
<
If i Mod 3 = 0 And i Mod 5 = 0 Then
Print("FizzBuzz")
Line 10,763 ⟶ 12,408:
Print(Str(i))
End If
Next</
An alternative syntax:
<syntaxhighlight lang="vb">
For i As Integer = 1 To 100
Select Case True
Line 10,777 ⟶ 12,422:
Print(Str(i))
End Select
Next</
=={{header|XPath 2.0}}==
<
concat('fizz'[not($n mod 3)], 'buzz'[not($n mod 5)], $n[$n mod 15 = (1,2,4,7,8,11,13,14)])</
...or alternatively...
<
($n, 'Fizz', 'Buzz', 'FizzBuzz')[number(($n mod 3) = 0) + number(($n mod 5) = 0)*2 + 1]</
=={{header|XPL0}}==
<
int N;
[for N:= 1 to 100 do
Line 10,795 ⟶ 12,440:
CrLf(0);
];
]</
{{out}}
<pre>
Line 10,823 ⟶ 12,468:
===XSLT 1.0===
{{works with|xsltproc|libxslt 10126}}
<
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="text" encoding="utf-8"/>
Line 10,875 ⟶ 12,520:
<xsl:call-template name="fizzbuzz-range"/>
</xsl:template>
</xsl:stylesheet></
===XSLT 1.0 With EXSLT===
<
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:exsl="http://exslt.org/common"
Line 10,909 ⟶ 12,554:
</xsl:template>
</xsl:stylesheet></
===XSLT 2.0===
<
<xsl:output method="text"/>
Line 10,921 ⟶ 12,566:
</xsl:template>
</xsl:stylesheet></
Line 10,927 ⟶ 12,572:
See [[FizzBuzz/Basic]]
=={{header|YAMLScript}}==
<syntaxhighlight lang="yaml">
#!/usr/bin/env ys-0
# This program has multiple implementations of "fizzbuzz".
# usage: yamlscript fizzbuzz.ys [<count>] [<fizzbuzz-fn-#>]
# The main function runs a certain requested fizzbuzz implementation function
# for a certain requested number (default is 100).
defn main(count=100 impl=1):
fizzbuzz =: "fizzbuzz-$impl"
when-not ENV.'YS_TEST':
say: "Running function '$fizzbuzz' with count=$count"
function =: resolve(fizzbuzz.symbol())
result =: function(count)
mapv say: result
# These implementation functions were adapted from
# https://rosettacode.org/wiki/FizzBuzz#Clojure
defn fizzbuzz-1(n):
map:
fn(x):
cond:
zero?(x % 15): 'FizzBuzz'
zero?(x % 5): 'Buzz'
zero?(x % 3): 'Fizz'
=>: x
=>: 1 .. n
defn fizzbuzz-2(n):
loop [i 1, l []]:
if (i > n):
=>: l
recur inc(i):
conj l:
cond:
zero?(i % 15): 'FizzBuzz'
zero?(i % 5): 'Buzz'
zero?(i % 3): 'Fizz'
=>: i
defn fizzbuzz-3(n):
map:
fn(x):
s =:
str:
when zero?(x % 3): 'Fizz'
=>: (zero?(x % 5) && 'Buzz') || nil
if empty?(s): x s
rng: 1 n
</syntaxhighlight>
{{out}}
<pre>
$ ys sample/fizzbuzz.ys 16 2
Running function 'fizzbuzz-2' with count=16
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
</pre>
=={{header|Yorick}}==
===Iterative solution===
<
if(i % 3 == 0)
write, format="%s", "Fizz";
Line 10,938 ⟶ 12,664:
write, format="%d", i;
write, "";
}</
===Vectorized solution===
<
output(3::3) = "Fizz";
output(5::5) = "Buzz";
output(15::15) = "FizzBuzz";
write, format="%s\n", output;</
=={{header|Z80 Assembly}}==
See [[FizzBuzz/Assembly]]
=={{header|Zig}}==
<syntaxhighlight lang="zig">const print = @import("std").debug.print;
pub fn main() void {
var i: usize = 1;
while (i <= 100) : (i += 1) {
if (i % 3 == 0 and i % 5 == 0) {
print("FizzBuzz\n", .{});
} else if (i % 3 == 0) {
print("Fizz\n", .{});
} else if (i % 5 == 0) {
print("Buzz\n", .{});
} else {
print("{}\n", .{i});
}
}
}</syntaxhighlight>
=={{header|zkl}}==
<
if(n % 3 == 0) print("Fizz");
if(not (n%5)) "Buzz".print();
if(n%3 and n%5) print(n);
println();
}</
Or, using infinite lazy sequences:
<
Walker.cycle("","","Fizz").zipWith(f,Walker.cycle("","","","","Buzz"),[1..])
.walk(100).concat("\n").println();</
More of the same:
<
.zipWith(fcn(a,b){ a or b },[1..]).walk(100).concat("\n").println();</
{{out}}
<pre>
Line 10,985 ⟶ 12,728:
=={{header|ZX Spectrum Basic}}==
{{trans|Applesoft BASIC}}
<
20 FOR a=1 TO 100
30 LET o$=""
Line 10,992 ⟶ 12,735:
60 IF o$="" THEN LET o$=STR$ a
70 PRINT o$
80 NEXT a</
|