FizzBuzz
From Rosetta Code
Puzzle
This is a programming puzzle. It lays out a problem which Rosetta Code users are encouraged to solve, using languages and techniques they know. Multiple approaches are not discouraged, so long as the puzzle guidelines are followed.
Code examples should be formatted along the lines of one of the existing prototypes.
For other Puzzles, see Category:PuzzlesWrite a program that prints the numbers from 1 to 100. But for multiples of three print "Fizz" instead of the number and for the multiples of five print "Buzz". For numbers which are multiples of both three and five print "FizzBuzz". [1]
FizzBuzz was presented as the lowest level of comprehension required to illustrate adequacy. [2]
[edit] Ada
with Ada.Text_Io; use Ada.Text_Io;
procedure Fizzbuzz is
begin
for I in 1..100 loop
if I mod 15 = 0 then
Put_Line("FizzBuzz");
elsif I mod 5 = 0 then
Put_Line("Buzz");
elsif I mod 3 = 0 then
Put_Line("Fizz");
else
Put_Line(Integer'Image(I));
end if;
end loop;
end Fizzbuzz;
[edit] ALGOL 68
main:(
FOR i TO 100 DO
printf(($gl$,
IF i %* 15 = 0 THEN
"FizzBuzz"
ELIF i %* 3 = 0 THEN
"Fizz"
ELIF i %* 5 = 0 THEN
"Buzz"
ELSE
i
FI
))
OD
)
Or simply:
FOR i TO 100 DO print(((i%*15=0|"FizzBuzz"|:i%*3=0|"Fizz"|:i%*5=0|"Buzz"|i),new line)) OD
[edit] APL
⎕IO←0
(L,'Fizz' 'Buzz' 'FizzBuzz')[¯1+(L×W=0)+W←(100×~0=W)+W←⊃+/1 2×0=3 5|⊂L←1+⍳100]
[edit] AWK
BEGIN {
for (NUM=1; NUM<=100; NUM++)
if (NUM % 15 == 0)
{print "FizzBuzz"}
else if (NUM % 3 == 0)
{print "Fizz"}
else if (NUM % 5 == 0)
{print "Buzz"}
else
{print NUM}
}
[edit] BASIC
Works with: QuickBasic version 4.5
[edit] If/else ladder approach
FOR A = 1 TO 100
IF A MOD 15 = 0 THEN
PRINT "FizzBuzz"
ELSE IF A MOD 3 = 0 THEN
PRINT "Fizz"
ELSE IF A MOD 5 = 0 THEN
PRINT "Buzz"
ELSE
PRINT A
END IF
NEXT A
[edit] Concatenation approach
FOR A = 1 TO 100
OUT$ = ""
IF A MOD 3 = 0 THEN
OUT$ = OUT& + "Fizz"
END IF
IF A MOD 5 = 0 THEN
OUT$ = OUT$ + "Buzz"
END IF
IF OUT$ = "" THEN
OUT$ = OUT$ + A
END IF
PRINT OUT$
NEXT A
See also: RapidQ
[edit] C
#include<stdio.h>
int main (void)
{
int i;
for (i = 1; i <= 100; i++)
{
if (!(i % 15))
printf ("FizzBuzz\n");
else if (!(i % 3))
printf ("Fizz\n");
else if (!(i % 5))
printf ("Buzz\n");
else
printf ("%d\n", i);
}
return 0;
}
[edit] C++
#include <iostream> using namespace std; int main () { int i; for (i = 0; i <= 100; i++) { if (!(i % 15)) cout << "FizzBuzz" << endl; else if (!(i % 3)) cout << "Fizz" << endl; else if (!(i % 5)) cout << "Buzz" << endl; else cout << i << endl; } return 0; }
Alternate version not using modulo 15:
#include <iostream> int main() { for (int i = 0; i <= 100; ++i) { bool fizz = !(i % 3); bool buzz = !(i % 5); if (fizz) std::cout << "Fizz"; if (buzz) std::cout << "Buzz"; if (!fizz && !buzz) std::cout << i; std::cout << std::endl; } }
[edit] Common Lisp
(defun fizzbuzz ()
(loop for x from 1 to 100 do
(print (cond ((zerop (mod x 15)) "FizzBuzz")
((zerop (mod x 3)) "Fizz")
((zerop (mod x 5)) "Buzz")
(t x)))))
(defun fizzbuzz ()
(loop for x from 1 to 100 do
(format t "~&~{~A~}"
(or (append (when (zerop (mod x 3)) '("Fizz"))
(when (zerop (mod x 5)) '("Buzz")))
(list x)))))
[edit] D
module fizzbuzz;
import std.stdio;
import std.string ;
// if-else
void fizzBuzz(int n) {
for(int i = 1 ; i <= n; i++)
if (!(i%15))
writef("FizzBuzz") ;
else if (!(i%3))
writef("Fizz") ;
else if (!(i%5))
writef("Buzz") ;
else
writef(i) ;
writefln() ;
}
// use switch case
void fizzBuzz_s(int n) {
for(int i = 1 ; i <= n; i++)
switch(i%15) {
case 0:
writef("FizzBuzz") ; break ;
case 3,6,9,12:
writef("Fizz") ; break ;
case 5,10:
writef("Buzz") ; break ;
default:
writef(i) ;
}
writefln() ;
}
// recursive with concatenation
string fizzBuzz_r(int n){
string s = "" ;
if (n == 0)
return s ;
if(!(n % 5))
s = "Buzz"~ s ;
if(!(n % 3))
s = "Fizz" ~ s ;
if (s == "")
s = toString(n) ;
return fizzBuzz_r(n-1) ~ s ;
}
// alternative recursive
string fizzBuzz_r2(int n){
return (n>0) ? fizzBuzz_r2(n-1) ~
(n % 15 ? n % 5 ? n % 3 ? toString(n) :"Fizz" : "Buzz" : "FizzBuzz")
: "";
}
void main() {
fizzBuzz(100) ;
fizzBuzz_s(100) ;
writefln(fizzBuzz_r(100)) ;
writefln(fizzBuzz_r2(100)) ;
for(int i = 1 ; i <= 100;i++)
writef("%s", i % 15 ? i % 5 ? i % 3 ? toString(i) :"Fizz" : "Buzz" : "FizzBuzz") ;
}
[edit] E
for i in 1..100 {
println(switch ([i % 3, i % 5]) {
match [==0, ==0] { "FizzBuzz" }
match [==0, _ ] { "Fizz" }
match [_, ==0] { "Buzz" }
match _ { i }
})
}
[edit] Factor
IN: fizzbuzz USING: math kernel io ; : divides? ( m n -- ? ) mod 0 = ; : fizz ( n -- str ) 3 divides? [ "Fizz" ] [ "" ] if ; : buzz ( n -- str ) 5 divides? [ "Buzz" ] [ "" ] if ; : fizzbuzz ( n -- str ) dup fizz over buzz append dup empty? [ nip ] [ drop number>string ] if ; : main ( -- ) 100 [ 1+ fizzbuzz print ] each ; MAIN: main
[edit] Forth
[edit] table-driven
: fizz ( n -- ) drop ." Fizz" ; : buzz ( n -- ) drop ." Buzz" ; : fb ( n -- ) drop ." FizzBuzz" ; : vector create does> ( n -- ) over 15 mod cells + @ execute ; vector .fizzbuzz ' fb , ' . , ' . , ' fizz , ' . , ' buzz , ' fizz , ' . , ' . , ' fizz , ' buzz , ' . , ' fizz , ' . , ' . ,
[edit] or the classic approach
: .fizzbuzz ( n -- ) 0 pad c! dup 3 mod 0= if s" Fizz" pad place then dup 5 mod 0= if s" Buzz" pad +place then pad c@ if drop pad count type else . then ; : zz ( n -- ) 1+ 1 do i .fizzbuzz cr loop ; 100 zz
[edit] Fortran
In ANSI FORTRAN 66 or later use structured IF-THEN-ELSE (example uses some ISO Fortran 90 features):
program fizzbuzz_if
integer :: i
do i = 1, 100
if (mod(i,15) == 0) then; print *, 'FizzBuzz'
else if (mod(i,3) == 0) then; print *, 'Fizz'
else if (mod(i,5) == 0) then; print *, 'Buzz'
else; print *, i
end if
end do
end program fizzbuzz_if
In ISO Fortran 90 or later use SELECT-CASE statement:
program fizzbuzz_select
integer :: i
do i = 1, 100
select case (mod(i,15))
case 0; print *, 'FizzBuzz'
case 3,6,9,12; print *, 'Fizz'
case 5,10; print *, 'Buzz'
case default; print *, i
end select
end do
end program fizzbuzz_select
[edit] Groovy
for (i in 1..100) {
println "${i%3?'':'Fizz'}${i%5?'':'Buzz'}" ?: i
}
[edit] Haskell
Variant directly implementing the specification:
output x | x3 && x5 = "FizzBuzz"
| x3 = "Fizz"
| x5 = "Buzz"
| otherwise = show x
where
x3 = x `mod` 3 == 0
x5 = x `mod` 5 == 0
answer = map output [1..100]
[edit] J
Solution 0
> }. (<'FizzBuzz') (I.0=15|n)} (<'Buzz') (I.0=5|n)} (<'Fizz') (I.0=3|n)} ":&.> n=: i.101
Solution 1
Fizz=: 'Fizz' #~ 0 = 3&|
Buzz=: 'Buzz' #~ 0 = 5&|
FizzBuzz=: ": [^:(''-:]) Fizz,Buzz
FizzBuzz"0 >: i.100
[edit] Java
[edit] If/else ladder
public class FizzBuzz{ public static void main(String[] args){ for(int i= 1; i <= 100; i++){ if(i % 15 == 0){ System.out.println("FizzBuzz"); }else if(i % 3 == 0){ System.out.println("Fizz"); }else if(i % 5 == 0){ System.out.println("Buzz"); }else{ System.out.println(i); } } } }
[edit] Concatenation
public class FizzBuzz{ public static void main(String[] args){ for(int i= 1; i <= 100; i++){ String output = ""; if(i % 3 == 0) output += "Fizz"; if(i % 5 == 0) output += "Buzz"; if(output.equals("")) output += i; System.out.println(output); } } }
[edit] Ternary operator
public class FizzBuzz{ public static void main(String[] args){ for(int i= 1; i <= 100; i++){ System.out.println(i % 15 != 0 ? i % 5 != 0 ? i % 3 != 0 ? i : "Fizz" : "Buzz" : "FizzBuzz" ;); } } }
[edit] Recursive
public String fizzBuzz(int n){ String s = ""; if (n == 0) return s; if((n % 5) == 0) s = "Buzz" + s; if((n % 3) == 0) s = "Fizz" + s; if (s.equals("")) s = n + ""; return fizzBuzz(n-1) + s; }
[edit] Alternative Recursive
public String fizzBuzz(int n){ return (n>0) ? fizzBuzz(n-1) + (n % 15 != 0? n % 5 != 0? n % 3 != 0? (n+"") :"Fizz" : "Buzz" : "FizzBuzz") : ""; }
[edit] JavaScript
Works with: NJS version 0.2.5
for (var i = 1; i <= 100; i++) {
if (i % 15 == 0) {
print("FizzBuzz");
} else if (i % 3 == 0) {
print("Fizz");
} else if (i % 5 == 0) {
print("Buzz");
} else {
print(i);
}
}
[edit] MAXScript
for i in 1 to 100 do
(
case of
(
(mod i 15 == 0): (print "FizzBuzz")
(mod i 5 == 0): (print "Buzz")
(mod i 3 == 0): (print "Fizz")
default: (print i)
)
)
[edit] Oberon-2
MODULE FizzBuzz;
IMPORT Out;
VAR i: INTEGER;
BEGIN
FOR i := 1 TO 100 DO
IF i MOD 15 = 0 THEN
Out.String("FizzBuzz");
Out.Ln;
ELSIF i MOD 5 = 0 THEN
Out.String("Buzz");
Out.Ln;
ELSIF i MOD 3 = 0 THEN
Out.String("Fizz");
Out.Ln;
ELSE
Out.Int(i,0);
Out.Ln;
END;
END;
END FizzBuzz.
[edit] OCaml
let output x = match x mod 3 = 0, x mod 5 = 0 with true, true -> "FizzBuzz" | true, false -> "Fizz" | false, true -> "Buzz" | false, false -> string_of_int x let _ = for i = 1 to 100 do print_endline (output i) done
[edit] Perl
foreach (1 .. 100) { if (0 == $_ % 15) { print "FizzBuzz\n"; } elsif (0 == $_ % 3) { print "Fizz\n"; } elsif (0 == $_ % 5) { print "Buzz\n"; } else { print "$_\n"; }; };
More concisely:
sub f { $_[0] % $_[1] ? '' : $_[2] } print f($_, 3, 'Fizz') . f($_, 5, 'Buzz') || $_, "\n" foreach 1 .. 100;
[edit] PHP
[edit] if/else ladder approach
<?php
for ($i = 1; $i <= 100; $i++)
{
if (!($i % 15))
echo "FizzBuzz\n";
else if (!($i % 3))
echo "Fizz\n";
else if (!($i % 5))
echo "Buzz\n";
else
echo "$i\n";
}
?>
[edit] 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.
<?php
for ( $i = 1; $i <= 100; ++$i )
{
$str = "";
if (!($i % 3 ) )
$str .= "Fizz";
if (!($i % 5 ) )
$str .= "Buzz";
if ( empty( $str ) )
$str = $i;
echo "$str\n";
}
?>
[edit] Pop11
lvars str;
for i from 1 to 100 do
if i rem 15 = 0 then
'FizzBuzz' -> str;
elseif i rem 3 = 0 then
'Fizz' -> str;
elseif i rem 5 = 0 then
'Buzz' -> str;
else
'' >< i -> str;
endif;
printf(str, '%s\n');
endfor;
[edit] PostScript
1 1 100 {
/c false def
dup 3 mod 0 eq { (Fizz) print /c true def } if
dup 5 mod 0 eq { (Buzz) print /c true def } if
c {pop}{( ) cvs print} ifelse
(\n) print
} for
or...
/fizzdict 100 dict def
fizzdict begin
/notmod{ ( ) cvs } def
/mod15 { dup 15 mod 0 eq { (FizzBuzz)def }{pop}ifelse} def
/mod3 { dup 3 mod 0 eq {(Fizz)def}{pop}ifelse} def
/mod5 { dup 5 mod 0 eq {(Buzz)def}{pop}ifelse} def
1 1 100 { mod3 } for
1 1 100 { mod5 } for
1 1 100 { mod15} for
1 1 100 { dup currentdict exch known { currentdict exch get}{notmod} ifelse print (\n) print} for
end
[edit] Python
for i in xrange(1, 101):
if i % 15 == 0:
print "FizzBuzz"
elif i % 3 == 0:
print "Fizz"
elif i % 5 == 0:
print "Buzz"
else:
print i
And a shorter version with less duplication:
for i in range(1, 101):
words = [word for n, word in ((3, 'Fizz'), (5, 'Buzz')) if not i % n]
print ''.join(words) or i
[edit] RapidQ
The BASIC solutions work with RapidQ, too.
However, here is a bit more esoteric solution using the IIF() function.
FOR i=1 TO 100
t$ = IIF(i MOD 3 = 0, "Fizz", "") + IIF(i MOD 5 = 0, "Buzz", "")
PRINT IIF(LEN(t$), t$, i)
NEXT i
[edit] Raven
100 each 1 + as n '' n 3 mod 0 = if 'Fizz' cat n 5 mod 0 = if 'Buzz' cat dup empty if drop n say
[edit] Ruby
1.upto(100) do |n| print "Fizz" if a = (n % 3).zero? print "Buzz" if b = (n % 5).zero? print n unless (a || b) print "\n" end
[edit] Scheme
(do ((i 1 (+ i 1))) ((> i 100)) (display (cond ((= 0 (modulo i 15)) "FizzBuzz") ((= 0 (modulo i 3)) "Fizz") ((= 0 (modulo i 5)) "Buzz") (else i))) (newline))
[edit] Seed7
$ include "seed7_05.s7i";
const proc: main is func
local
var integer: number is 0;
begin
for number range 1 to 100 do
if number rem 15 = 0 then
writeln("FizzBuzz");
elsif number rem 5 = 0 then
writeln("Buzz");
elsif number rem 3 = 0 then
writeln("Fizz");
else
writeln(number);
end if;
end for;
end func;
[edit] Smalltalk
Since only GNU Smalltalk supports file-based programming, we'll be using its syntax.
Integer extend [
fizzbuzz [
| fb |
fb := '%<Fizz|>1%<Buzz|>2' % {
self \\ 3 == 0. self \\ 5 == 0 }.
^fb isEmpty ifTrue: [ self ] ifFalse: [ fb ]
]
]
1 to: 100 do: [ :i | i fizzbuzz displayNl ]
[edit] V
[fizzbuzz
1 [>=] [
[[15 % zero?] ['fizzbuzz' puts]
[5 % zero?] ['buzz' puts]
[3 % zero?] ['fizz' puts]
[true] [dup puts]
] when succ
] while].
|100 fizzbuzz
[edit] Second try
(a compiler for fizzbuzz)
define a command that will generate a sequence
[seq [] swap dup [zero? not] [rolldown [dup] dip cons rollup pred] while pop pop].
create a quote that will return a quote that returns a quote if its argument is an integer (A HOF)
[check [N X F : [[integer?] [[X % zero?] [N F cons] if] if]] view].
Create a quote that will make sure that the above quote is applied correctly if given (Number Function) as arguments.
[func [[N F] : [dup N F check i] ] view map].
And apply it
100 seq [
[15 [pop 'fizzbuzz' puts]]
[5 [pop 'buzz' puts]]
[3 [pop 'fizz' puts]]
[1 [puts]]] [func dup] step
[i true] map pop
the first one is much better :)
[edit] Visual Basic .NET
Platform: .NET
Works with: Visual Basic .NET version 9.0+
Sub Main()
For i = 1 To 100
If i Mod 15 = 0 Then
Console.WriteLine("FizzBuzz")
ElseIf i Mod 5 = 0 Then
Console.WriteLine("Buzz")
ElseIf i Mod 3 = 0 Then
Console.WriteLine("Fizz")
Else
Console.WriteLine(i)
End If
Next
End Sub
[edit] UNIX Shell
for n in `seq 1 100`; do
if [ $(($n % 15)) = 0 ]; then
echo FizzBuzz
elif [ $(($n % 3)) = 0 ]; then
echo Fizz
elif [ $(($n % 5)) = 0 ]; then
echo Buzz
else
echo $n
fi
done
A more portable version:
NUM=1
until (($NUM==101)) ; do
if (($NUM % 15 == 0)) ; then
echo FizzBuzz
elif (($NUM % 3 == 0)) ; then
echo Fizz
elif (($NUM % 5 == 0)) ; then
echo Buzz
else
echo "$NUM"
fi
((NUM=$NUM+1))
done
Categories: Recursion | Programming Tasks | Puzzles | Ada | ALGOL 68 | APL | AWK | BASIC | C | C++ | Common Lisp | D | E | Factor | Forth | Fortran | Groovy | Haskell | J | Java | JavaScript | MAXScript | Oberon-2 | OCaml | Perl | PHP | Pop11 | PostScript | Python | RapidQ | Raven | Ruby | Scheme | Seed7 | Smalltalk | V | Visual Basic .NET | UNIX Shell

