# 99 bottles of beer

99 bottles of beer
You are encouraged to solve this task according to the task description, using any language you may know.
The beersong

In this puzzle, write code to print out the entire "99 bottles of beer on the wall" song.

For those who do not know the song, the lyrics follow this form:

X bottles of beer on the wall
X bottles of beer
Take one down, pass it around
X-1 bottles of beer on the wall

X-1 bottles of beer on the wall
...
Take one down, pass it around
0 bottles of beer on the wall


Where X and X-1 are replaced by numbers of course. Grammatical support for "1 bottle of beer" is optional. As with any puzzle, try to do it in as creative/concise/comical a way as possible (simple, obvious solutions allowed, too).

## ABAP

<lang ABAP>REPORT z99bottles.

DATA lv_no_bottles(2) TYPE n VALUE 99.

DO lv_no_bottles TIMES.

 WRITE lv_no_bottles NO-ZERO.
WRITE ' bottles of beer on the wall'.
NEW-LINE.
WRITE lv_no_bottles NO-ZERO.
WRITE ' bottles of beer'.
NEW-LINE.
WRITE 'Take one down, pass it around'.
NEW-LINE.
SUBTRACT 1 FROM lv_no_bottles.
WRITE lv_no_bottles NO-ZERO.
WRITE ' bottles of beer on the wall'.
WRITE /.


ENDDO.</lang>

## ActionScript

<lang ActionScript>for(var numBottles:uint = 99; numBottles > 0; numBottles--) { trace(numBottles, " bottles of beer on the wall"); trace(numBottles, " bottles of beer"); trace("Take one down, pass it around"); trace(numBottles - 1, " bottles of beer on the wall\n"); }</lang>

### Simple version

procedure Bottles is
begin
for X in reverse 1..99 loop
Put_Line(Integer'Image(X) & " bottles of beer on the wall");
Put_Line(Integer'Image(X) & " bottles of beer");
Put_Line("Take one down, pass it around");
Put_Line(Integer'Image(X - 1) & " bottles of beer on the wall");
New_Line;
end loop;
end Bottles;</lang>


### Concurrent version

  subtype Num_Bottles is Natural range 1..99;
entry Set (Num_Bottles);
end Print;
Num : Natural;
begin
for I in reverse Num_Bottles'range loop
select
accept
Set(I) do -- Rendezvous with Counter task I
Num := I;
end Set;
Put_Line(Integer'Image(Num) & " bottles of beer on the wall");
Put_Line(Integer'Image(Num) & " bottles of beer");
Put_Line("Take one down, pass it around");
Put_Line(Integer'Image(Num - 1) & " bottles of beer on the wall");
New_Line;
or terminate; -- end when all Counter tasks have completed
end select;
end loop;
end Print;
begin
Print.Set(I);
end Counter;



begin

  for I in Task_List'range loop -- Create 99 Counter tasks
end loop;


## Aime

<lang aime>integer main(void) {

   cardinal bottles;

   bottles = 99;

   do {


o_cardinal(bottles);

       o_text(" bottles of beer on the wall\n");


o_cardinal(bottles);

       o_text(" bottles of beer\n");
o_text("Take one down, pass it around\n");
bottles -= 1;


o_cardinal(bottles);

       o_text(" bottles of beer on the wall\n\n");
} while (bottles);

   return 0;


}</lang>

## ALGOL 68

Works with: ALGOL 68 version Standard - no extensions to language used
Works with: ALGOL 68G version Any - tested with release mk15-0.8b.fc9.i386

<lang algol68>main:(

  FOR bottles FROM 99 TO 1 BY -1 DO
printf(($z-d" bottles of beer on the wall"l$, bottles));
printf(($z-d" bottles of beer"l$, bottles));
printf(($"Take one down, pass it around"l$));
printf(($z-d" bottles of beer on the wall"ll$, bottles-1))
OD


)</lang>

## AmigaE

<lang amigae>PROC main()

 DEF t: PTR TO CHAR,
s: PTR TO CHAR,
u: PTR TO CHAR, i, x
t := 'Take one down, pass it around\n'
s := '\d bottle\s of beer\s\n'
u := ' on the wall'
FOR i := 99 TO 0 STEP -1
ForAll({x}, [u, NIL], WriteF(s, i, IF i <> 1 THEN 's' ELSE NIL,
x))
IF i > 0 THEN WriteF(t)
ENDFOR


ENDPROC</lang>

## Apache Ant

Implementation in Apache Ant, due to the limitations of Ant, this requires ant-contrib for arithmetic operations and a dummy target to keep Ant from detecting the loop. <lang xml><?xml version="1.0"?> <project name="n bottles" default="99_bottles">

 <taskdef resource="net/sf/antcontrib/antcontrib.properties"/>

 <property name="count" value="99"/>

 <target name="99_bottles">
<antcall target="bottle">
<param name="number" value="${count}"/> </antcall> </target>   <target name="bottle"> <echo message="${number} bottles of beer on the wall"/>
<echo message="${number} bottles of beer"/> <echo message="Take one down, pass it around"/>   ${\displaystyle }$   <echo message="${result} bottles of beer on the wall"/>

   <if>
<not><equals arg1="${result}" arg2="0" /></not> <then> <antcall target="bottleiterate"> <param name="number" value="${result}"/>
</antcall>
</then>
</if>
</target>

 <target name="bottleiterate">
<antcall target="bottle">
<param name="number" value="${number}"/> </antcall> </target>  </project></lang> ## APL Works with: Dyalog APL Translation of: J  bob ← { (⍕⍵), ' bottle', (1=⍵)↓'s of beer'} bobw ← {(bob ⍵) , ' on the wall'} beer ← { (bobw ⍵) , ', ', (bob ⍵) , '; take one down and pass it around, ', bobw ⍵-1} ↑beer¨ ⌽(1-⎕IO)+⍳99  ## App Inventor ### Using a 'for each <number>' block (simplest) Note that the output label text is not displayed until the entire lyrics text has been built and there is some delay between button press and display. <CLICK HERE TO VIEW THE BLOCKS AND OUTPUT> ### Using a Clock Timer block (preferrred) Output can be sent directly to a label with this preferred method as there is no noticeable delay between button press and output. <CLICK HERE TO VIEW THE BLOCKS AND OUTPUT> ## AppleScript <lang Applescript>repeat with beerCount from 99 to 1 by -1  set bottles to "bottles" if beerCount < 99 then if beerCount = 1 then set bottles to "bottle" end log "" & beerCount & " " & bottles & " of beer on the wall" log "" end log "" & beerCount & " " & bottles & " of beer on the wall" log "" & beerCount & " " & bottles & " of beer" log "Take one down, pass it around"  end log "No more bottles of beer on the wall!"</lang> ## Arbre <lang Arbre> bottle(x):  template: '$x bottles of beer on the wall.
$x bottles of beer. Take one down and pass it around,$y bottles of beer on the wall.
'

 if x==0
template~{x: 'No more', y: 'No more'}
else
if x==1
template~{x: x, y: 'No more'}
else
template~{x: x, y: x-1}


bottles(n):

 for x in [n..0]
bottle(x)


99bottles():

 bottles(99) -> io


</lang>

## Argile

<lang Argile>use std

let X be an int for each X from 99 down to 1

 prints X bottles of beer on the wall
prints X bottles of beer
prints "Take one down, pass it" around
if X == 1
echo No more "beer." Call da "amber lamps"
break
X--
prints X bottles of beer on the wall "\n"
X++
.:around :. -> text {X>59 ? "around", "to me"}
.:bottles:. -> text {X> 5 ? "bottles", (X>1 ? "buttles", "wall")}
.:of beer:. -> text {X>11 ? "of beer", "ov beeer"}
.:on the wall:. -> text {
X>17 ? "on the wall", (X>1 ? "on the bwall", "in the buttle")
}</lang>


## ATS

<lang ATS>//

1. include

"share/atspre_staload.hats" // (* ****** ****** *)

fun bottles

 (n0: int): void = let


// fun loop (n: int): void = (

 if n > 0 then
(
if n0 > n then println! ();
println! (n, " bottles of beer on the wall");
println! (n, " bottles of beer");
println! ("Take one down, pass it around");
println! (n-1, " bottles of beer on the wall");
loop (n - 1)
) (* end of [if] *)


) // in

 loop (n0)


end // end of [bottles]

(* ****** ****** *)

implement main0 () = bottles (99)</lang>

## AWK

### Regular version

If you don't want so many beers, here you can specify the starting amount.
For example, just a sixpack:

<lang awk># usage: gawk -v i=6 -f beersong.awk

function bb(n) { b = " bottles of beer" if( n==1 ) { sub("s","",b) } if( n==0 ) { n="No more" } return n b }

BEGIN { if( !i ) { i = 99 } ow = "on the wall" td = "Take one down, pass it around." print "The beersong:\n" while (i > 0) { printf( "%s %s,\n%s.\n%s\n%s %s.\n\n", bb(i), ow, bb(i), td, bb(--i), ow ) if( i==1 ) sub( "one","it", td ) } print "Go to the store and buy some more!" }</lang>

Output:
The beersong:

99 bottles of beer on the wall,
99 bottles of beer.
Take one down, pass it around.
98 bottles of beer on the wall.

...

3 bottles of beer on the wall,
3 bottles of beer.
Take one down, pass it around.
2 bottles of beer on the wall.

2 bottles of beer on the wall,
2 bottles of beer.
Take one down, pass it around.
1 bottle of beer on the wall.

1 bottle of beer on the wall,
1 bottle of beer.
Take it down, pass it around.
No more bottles of beer on the wall.

Go to the store and buy some more!


## Babel

<lang babel>main: { 99 bottles }

bottles!:

   { x set
{ bw
bx cr <<
"Take one down, pass it around\n" <<
1 x -=
bw "\n" << }
x times }


b  : " bottles of beer" bx!: { x %d << b } w  : " on the wall" bw!: { bx w . cr << }

x: [0]</lang>

## Battlestar

<lang c> const bottle = " bottle" const plural = "s" const ofbeer = " of beer" const wall = " on the wall" const sep = ", " const takedown = "Take one down and pass it around, " const u_no = "No" const l_no = "no" const more = " more bottles of beer" const store = "Go to the store and buy some more, " const dotnl = ".\n" const nl = "\n"

// Print two digits, use the value in a fun printnum

   b = a
loop
break (a < 10)
a /= 10
// modulo is in the d register after idiv
b = d
a += 48 // ASCII value for '0'
print(chr(a))
break
end
a = b
a += 48 // ASCII value for '0'
print(chr(a))


end

fun main

   loop 99
// Save loop counter for later, twice
c -> stack
c -> stack

       // Print the loop counter (passed in the a register)
a = c
printnum()

       // N, "bottles of beer on the wall, "
print(bottle)
print(plural)
print(ofbeer)
print(wall)
print(sep)

       // Retrieve and print the number
stack -> a
printnum()

       // N, "bottles of beer."
print(bottle)
print(plural)
print(ofbeer)
print(dotnl)

       // "Take one down and pass it around,"
print(takedown)

       // N-1, "bottles of beer on the wall."
stack -> a
a--
// Store N-1, used just a few lines down
a -> stack
printnum()
print(bottle)
// Retrieve N-1
stack -> a
// Write an "s" if the count is not 1
a != 1
print(plural)
end
// Write the rest
print(ofbeer)
print(wall)
print(dotnl)

       // Blank line
print(nl)

       // Skip to the top of the loop while the counter is >= 2
continue (c >= 2)

       // At the last two

       // "1 bottle of beer on the wall,"
a = 1
printnum()
print(bottle)
print(ofbeer)
print(wall)
print(sep)

       // "1 bottle of beer."
a = 1
printnum()
print(bottle)
print(ofbeer)
print(dotnl)

       // "Take one down and pass it around,"
print(takedown)

       // "no more bottles of beer on the wall."
print(l_no)
print(more)
print(wall)
print(dotnl)

       // Blank line
print(nl)

       // "No more bottles of beer on the wall,"
print(u_no)
print(more)
print(wall)
print(sep)

       // "no more bottles of beer."
print(l_no)
print(more)
print(dotnl)

       // "Go to the store and buy some more,"
print(store)

       // "99 bottles of beer on the wall."
a = 99
printnum()
print(bottle)
print(plural)
print(ofbeer)
print(wall)
print(dotnl)
end


end

// vim: set syntax=c ts=4 sw=4 et: </lang>

## Bracmat

Copy the code to a file called BottlesOfBeer.bra. Start Bracmat and after the {?} prompt write get$"BottlesOfBeer.bra" <Enter>. Then, after the next prompt, write !r <Enter>. Notice that the lyrics has two more lines at the end: No more bottles of beer on the wall, no more bottles of beer. Go to the store and buy some more, 99 bottles of beer on the wall. Code to save to BottlesOfBeer.bra: <lang bracmat>{BottlesOfBeer.bra X=  new  = n upper nbottles lyrics  . 99:?n & ( upper = .@(!arg:%@?a ?z)&str$(upp$!a !z) ) & ( nbottles = . str$ ( (   !arg:>0
&   !arg
" bottle"
(!arg:1&|s)
| "no more bottles"
)
" of beer"
)
)
& ( lyrics
=   (upper$(nbottles$!n:?x) " on the wall, " !x ".\n")
(   !n+-1:?n:~<0
&   "Take one down and pass it around, "
nbottles$!n " on the wall.  "  !lyrics | "Go to the store and buy some more, " nbottles$99
" on the wall.


"

         )
)
& put$(str$!lyrics);


r=

 get'"BottlesOfBeer.bra"


& rmv$(str$(BottlesOfBeer ".bak")) & ren$("BottlesOfBeer.bra".str$(BottlesOfBeer ".bak")) & put

 $( "{BottlesOfBeer.bra  "  , "BottlesOfBeer.bra" , NEW )  & lst'(X,"BottlesOfBeer.bra",APP) & put'(\n,"BottlesOfBeer.bra",APP) & lst'(r,"BottlesOfBeer.bra",APP) & put$(str$("\nnew'" X ";\n"),"BottlesOfBeer.bra",APP); new'X; </lang> ## Brainf*** ## Brat <lang brat>99.to 2 { n |  p "#{n} bottles of beer on the wall, #{n} bottles of beer!" p "Take one down, pass it around, #{n - 1} bottle#{true? n > 2 's' } of beer on the wall."  } p "One bottle of beer on the wall, one bottle of beer!" p "Take one down, pass it around, no more bottles of beer on the wall."</lang> ## C Translation of: C++ ### The simple solution <lang c>#include <stdlib.h> 1. include <stdio.h> int main(void) {  unsigned int bottles = 99; do { printf("%u bottles of beer on the wall\n", bottles); printf("%u bottles of beer\n", bottles); printf("Take one down, pass it around\n"); printf("%u bottles of beer on the wall\n\n", --bottles); } while(bottles > 0); return EXIT_SUCCESS;  }</lang> ### A recursive solution <lang c>#include <stdio.h> int main(int argc, char *argv[]) {  if(argc == 99) return 99; if(argv[0] != NULL){ argv[0] = NULL; argc = 0; } argc = main(argc + 1, argv); printf("%d bottle%c of beer on the wall\n", argc, argc == 1?'\0': 's'); printf("%d bottle%c of beer\n", argc, argc == 1?'\0': 's'); printf("Take one down, pass it around\n"); printf("%d bottle%c of beer on the wall\n\n", argc - 1, (argc - 1) == 1?'\0': 's'); return argc - 1;  }</lang> ### Code golf <lang c>#include <stdio.h> main(){_=100;while(--_)printf("%i bottle%s of beer in the wall,\n%i bottle%" "s of beer.\nTake one down, pass it round,\n%s%s\n\n",_,_-1?"s":"",_,_-1?"s" "",_-1?(char[]){(_-1)/10?(_-1)/10+48:(_-1)%10+48,(_-1)/10?(_-1)%10+48:2+30, (_-1)/10?32:0,0}:"",_-1?"bottles of beer in the wall":"No more beers");}</lang> ### A preprocessor solution Of course, with the template metaprogramming solution, the program has still do the conversion of numbers to strings at runtime, and those function calls also cost unnecessary time. Couldn't we just compose the complete text at compile time, and just output it at run time? Well, with the preprocessor, that's indeed possible: <lang c>#include <stdlib.h> 1. include <stdio.h> 1. define BOTTLE(nstr) nstr " bottles of beer" 1. define WALL(nstr) BOTTLE(nstr) " on the wall" 1. define PART1(nstr) WALL(nstr) "\n" BOTTLE(nstr) \  "\nTake one down, pass it around\n"  1. define PART2(nstr) WALL(nstr) "\n\n" 1. define MIDDLE(nstr) PART2(nstr) PART1(nstr) 1. define SONG PART1("100") CD2 PART2("0") 1. define CD2 CD3("9") CD3("8") CD3("7") CD3("6") CD3("5") \  CD3("4") CD3("3") CD3("2") CD3("1") CD4("")  1. define CD3(pre) CD4(pre) MIDDLE(pre "0") 1. define CD4(pre) MIDDLE(pre "9") MIDDLE(pre "8") MIDDLE(pre "7") \ MIDDLE(pre "6") MIDDLE(pre "5") MIDDLE(pre "4") MIDDLE(pre "3") \ MIDDLE(pre "2") MIDDLE(pre "1")  int main(void) {  (void) printf(SONG); return EXIT_SUCCESS;  }</lang> An inspection of the generated executable proves that it indeed contains the complete text of the song in one block. ### The bottled version WYSIWYG (with correct plurals and can buy some more):<lang c> int b =99,u =1;  #include<stdio.h> char *d[16],y[] = "#:ottle/ of" ":eer_ a_Go<o5" "st>y\x20some6" "_Take8;down4p" "a=1rou7_17 _<" "h;_ m?_nd_ on" "_085wal" "l_ " "b_e _ t_ss it" "_?4bu_ore_9, " "\060.""@, 9$";
# define x  c  ^=
#include <string.h>
#define or(t,z) else\
if(c==t && !(c = 0) &&\
(c =! z)); int p(char *t)


{ char *s = t; int c; for ( d[c = 0] = y; !t && (d[c +1 ]= strchr(s = d[c], '_'));* (d[++c]++) = 0); for(t = s? s:t;(c= *s++); c && putchar (c)) { if (!((( x 48)& ~0xf ) && ( x 48)) ) p(d[c]), c= 0 ; or('$', p(b - 99?".\n": "." ) && p(b - 99? t : "")) or ('\x40', c && p( d[!!b-- + 2])) or('/', c && p( b^1? "s": "")) or ('\043', b++ ? p("So6" + --b):!printf("%d" , b ? --b : (b += 99))) or( 'S',!(++u % 3) * 32+ 78) or ('.', puts("."))}return c;} int main() {return p(0);}</lang>  ## C++ ### The simple solution Works with: g++ version 4.8.1 <lang cpp>#include <iostream> using std::cout; int main() {  for(int bottles(99); bottles > 0; bottles -= 1){ cout << bottles << " bottles of beer on the wall\n" << bottles << " bottles of beer\n" << "Take one down, pass it around\n" << bottles - 1 << " bottles of beer on the wall\n\n"; }  }</lang> ### An object-oriented solution ### A template metaprogramming solution Of course, the output of the program always looks the same. One may therefore question why the program has to do all that tedious subtracting during runtime. Couldn't the compiler just generate the code to output the text, with ready-calculated constants? Indeed, it can, and the technique is called template metaprogramming. The following short code gives the text without containing a single variable, let alone a loop: <lang cpp>#include <iostream> template<int max, int min> struct bottle_countdown {  static const int middle = (min + max)/2; static void print() { bottle_countdown<max, middle+1>::print(); bottle_countdown<middle, min>::print(); }  }; template<int value> struct bottle_countdown<value, value> {  static void print() { std::cout << value << " bottles of beer on the wall\n" << value << " bottles of beer\n" << "Take one down, pass it around\n" << value-1 << " bottles of beer\n\n"; }  }; int main() {  bottle_countdown<100, 1>::print(); return 0;  }</lang> ### A Recursive solution <lang cpp>#include <iostream> using namespace std; void rec(int bottles) { if ( bottles!=0) { cout << bottles << " bottles of beer on the wall" << endl; cout << bottles << " bottles of beer" << endl; cout << "Take one down, pass it around" << endl; cout << --bottles << " bottles of beer on the wall\n" << endl; rec(bottles); }  } int main() {  rec(99); system("pause"); return 0; } </lang> ### A preprocessor solution Of course, with the template metaprogramming solution, the program has still do the conversion of numbers to strings at runtime, and those function calls also cost unnecessary time. Couldn't we just compose the complete text at compile time, and just output it at run time? Well, with the preprocessor, that's indeed possible: <lang cpp>#include <iostream> 1. include <ostream> 1. define BOTTLE(nstr) nstr " bottles of beer" 1. define WALL(nstr) BOTTLE(nstr) " on the wall" 1. define PART1(nstr) WALL(nstr) "\n" BOTTLE(nstr) \  "\nTake one down, pass it around\n"  1. define PART2(nstr) WALL(nstr) "\n\n" 1. define MIDDLE(nstr) PART2(nstr) PART1(nstr) 1. define SONG PART1("100") CD2 PART2("0") 1. define CD2 CD3("9") CD3("8") CD3("7") CD3("6") CD3("5") \  CD3("4") CD3("3") CD3("2") CD3("1") CD4("")  1. define CD3(pre) CD4(pre) MIDDLE(pre "0") 1. define CD4(pre) MIDDLE(pre "9") MIDDLE(pre "8") MIDDLE(pre "7") \ MIDDLE(pre "6") MIDDLE(pre "5") MIDDLE(pre "4") MIDDLE(pre "3") \ MIDDLE(pre "2") MIDDLE(pre "1")  int main() {  std::cout << SONG; return 0;  }</lang> ### Bottled Version <lang cpp> //>,_  //Beer Song>,_ #include <iostream> using namespace std; int main(){ for( int b=-1; b<99; cout << '\n') for ( int w=0; w<3; cout << ".\n"){ if (w==2) cout << (( b--) ?"Take one dow" "n and pass it arou" "nd":"Go to the sto" "re and buy some mo" "re"); if (b<0) b=99 ; do{ if (w) cout << ", "; if (b) cout << b; else cout << ( (w) ? 'n' : 'N') << "o more"; cout << " bottle" ; if (b!=1) cout << 's' ; cout << " of beer"; if (w!=1) cout << " on th" "e wall" ;} while (!w++);} return 0 ; } // // by barrym 2011-05-01 // no bottles were harmed in the // making of this program!!!</lang>  ## C# <lang csharp>using System; class Program {  static void Main(string[] args) { for (int i = 99; i > -1; i--) { if (i == 0) { Console.WriteLine("No more bottles of beer on the wall, no more bottles of beer."); Console.WriteLine("Go to the store and buy some more, 99 bottles of beer on the wall."); break; } if (i == 1) { Console.WriteLine("1 bottle of beer on the wall, 1 bottle of beer."); Console.WriteLine("Take one down and pass it around, no more bottles of beer on the wall."); Console.WriteLine(); } else { Console.WriteLine("{0} bottles of beer on the wall, {0} bottles of beer.", i); Console.WriteLine("Take one down and pass it around, {0} bottles of beer on the wall.", i - 1); Console.WriteLine(); } } }  }</lang> ### Another Implementation using Linq Works with: C# version 3+ <lang csharp>using System; using System.Linq; class Program {  static void Main() { var query = from total in Enumerable.Range(0,100).Reverse() select (total > 0) ? string.Format("{0} bottles of beer on the wall\n{0} bottles of beer\nTake one down, pass it around", total) : string.Format("{0} bottles left", total); foreach (var item in query) { Console.WriteLine(item); } }  }</lang> ### Flexible Version <lang csharp>  class Program { const string Vessel = "bottle"; const string Beverage = "beer"; const string Location = "on the wall";   private static string DefaultAction(ref int bottles) { bottles--; return "take one down, pass it around,"; }   private static string FallbackAction(ref int bottles) { bottles += 99; return "go to the store, buy some more,"; }   private static string Act(ref int bottles) { return bottles > 0 ? DefaultAction(ref bottles) : FallbackAction(ref bottles); }   static void Main() { Func<int, string> plural = b => b == 1 ? "" : "s"; Func<int, string> describeCount = b => b == 0 ? "no more" : b.ToString(); Func<int, string> describeBottles = b => string.Format("{0} {1}{2} of {3}", describeCount(b), Vessel, plural(b), Beverage); Action<string> write = s => Console.WriteLine(CultureInfo.CurrentCulture.TextInfo.ToTitleCase(s)); int bottles = 99; while (true) { write(string.Format("{0} {1}, {0},", describeBottles(bottles), Location)); write(Act(ref bottles)); write(string.Format("{0} {1}.", describeBottles(bottles), Location)); write(string.Empty); } } }  </lang> ### Using Formatting Works with: C# version 3+ <lang csharp> class songs {  static void Main(string[] args) { beer(5); }   private static void beer(int bottles) { for (int i = bottles; i > 0; i--) { if (i > 1) { Console.Write("{0}\n{1}\n{2}\n{3}\n\n", i + " bottles of beer on the wall", i + " bottles of beer", "Take one down, pass it around", (i - 1) + " bottles of beer on the wall"); } else Console.Write("{0}\n{1}\n{2}\n{3}\n\n", i + " bottle of beer on the wall", i + " bottle of beer", "Take one down, pass it around", (i - 1) + " bottles of beer on the wall...."); } }  }</lang> Output: 5 bottles of beer on the wall 5 bottles of beer Take one down, pass it around 4 bottles of beer on the wall 4 bottles of beer on the wall 4 bottles of beer Take one down, pass it around 3 bottles of beer on the wall 3 bottles of beer on the wall 3 bottles of beer Take one down, pass it around 2 bottles of beer on the wall 2 bottles of beer on the wall 2 bottles of beer Take one down, pass it around 1 bottles of beer on the wall 1 bottle of beer on the wall 1 bottle of beer Take one down, pass it around 0 bottles of beer on the wall....  ### Using iterator blocks Works with: C# version 3+ <lang csharp>using System; using System.Linq; class Program {  static void Main() { BeerBottles().Take(99).ToList().ForEach(Console.WriteLine); }   static IEnumerable<String> BeerBottles() { int i = 100; String f = "{0}, {1}. Take one down, pass it around, {2}"; Func<int, bool, String> booze = (c , b) => String.Format("{0} bottle{1} of beer{2}", c > 0 ? c.ToString() : "no more", (c == 1 ? "" : "s"), b ? " on the wall" : "");   while (--i >= 1) yield return String.Format(f, booze(i, true), booze(i, false), booze(i - 1, true)); }  }</lang> ### A Fun One <lang csharp> string[] bottles = { "80 Shilling", "Abita Amber", "Adams Broadside Ale", "Altenmünster Premium", "August Schell's SnowStorm", "Bah Humbug! Christmas Ale", "Beck's Oktoberfest", "Belhaven Wee Heavy", "Bison Chocolate Stout", "Blue Star Wheat Beer", "Bridgeport Black Strap Stout", "Brother Thelonius Belgian-Style Abbey Ale", "Capital Blonde Doppelbock", "Carta Blanca", "Celis Raspberry Wheat", "Christian Moerlein Select Lager", "Corona", "Czechvar", "Delirium Tremens", "Diamond Bear Southern Blonde", "Don De Dieu", "Eastside Dark", "Eliot Ness", "Flying Dog K-9 Cruiser Altitude Ale", "Fuller's London Porter", "Gaffel Kölsch", "Golden Horseshoe", "Guinness Pub Draught", "Hacker-Pschorr Weisse", "Hereford & Hops Black Spring Double Stout", "Highland Oatmeal Porter", "Ipswich Ale", "Iron City", "Jack Daniel's Amber Lager", "Jamaica Sunset India Pale Ale", "Killian's Red", "König Ludwig Weiss", "Kronenbourg 1664", "Lagunitas Hairy Eyball Ale", "Left Hand Juju Ginger", "Locktender Lager", "Magic Hat Blind Faith", "Missing Elf Double Bock", "Muskoka Cream Ale ", "New Glarus Cherry Stout", "Nostradamus Bruin", "Old Devil", "Ommegang Three Philosophers", "Paulaner Hefe-Weizen Dunkel", "Perla Chmielowa Pils", "Pete's Wicked Springfest", "Point White Biere", "Prostel Alkoholfrei", "Quilmes", "Rahr's Red", "Rebel Garnet", "Rickard's Red", "Rio Grande Elfego Bock", "Rogue Brutal Bitter", "Roswell Alien Amber Ale", "Russian River Pliny The Elder", "Samuel Adams Blackberry Witbier", "Samuel Smith's Taddy Porter", "Schlafly Pilsner", "Sea Dog Wild Blueberry Wheat Ale", "Sharp's", "Shiner 99", "Sierra Dorada", "Skullsplitter Orkney Ale", "Snake Chaser Irish Style Stout", "St. Arnold Bock", "St. Peter's Cream Stout", "Stag", "Stella Artois", "Stone Russian Imperial Stout", "Sweetwater Happy Ending Imperial Stout", "Taiwan Gold Medal", "Terrapin Big Hoppy Monster", "Thomas Hooker American Pale Ale", "Tie Die Red Ale", "Toohey's Premium", "Tsingtao", "Ugly Pug Black Lager", "Unibroue Qatre-Centieme", "Victoria Bitter", "Voll-Damm Doble Malta", "Wailing Wench Ale", "Warsteiner Dunkel", "Wellhead Crude Oil Stout", "Weyerbacher Blithering Idiot Barley-Wine Style Ale", "Wild Boar Amber", "Würzburger Oktoberfest", "Xingu Black Beer", "Yanjing", "Younger's Tartan Special", "Yuengling Black & Tan", "Zagorka Special", "Zig Zag River Lager", "Zywiec" }; int bottlesLeft = 99; const int FIRST_LINE_SINGULAR = 98; const int FINAL_LINE_SINGULAR = 97; string firstLine = ""; string finalLine = ""; for (int i = 0; i < 99; i++) { firstLine = bottlesLeft.ToString() + " bottle"; if (i != FIRST_LINE_SINGULAR) firstLine += "s"; firstLine += " of beer on the wall, " + bottlesLeft.ToString() + " bottle"; if (i != FIRST_LINE_SINGULAR) firstLine += "s"; firstLine += " of beer"; Console.WriteLine(firstLine); Console.WriteLine("Take the " + bottles[i] + " down, pass it around,"); bottlesLeft--; finalLine = bottlesLeft.ToString() + " bottle"; if (i != FINAL_LINE_SINGULAR) finalLine += "s"; finalLine += " of beer on the wall!"; Console.WriteLine(finalLine); Console.WriteLine(); Console.ReadLine(); } </lang> ### Using recursion <lang csharp>  public static void BottlesSong(int numberOfBottles) { if (numberOfBottles > 0) { Console.WriteLine("{0} bottles of beer on the wall", numberOfBottles); Console.WriteLine("{0} bottles of beer ", numberOfBottles); Console.WriteLine("Take one down, pass it around"); Console.WriteLine("{0} bottles of beer ", numberOfBottles - 1); Console.WriteLine(); BottlesSong(--numberOfBottles); } }  </lang> ## Clay <lang Clay>/* A few options here: I could give n type Int; or specify that n is of any  numeric type; but here I just let it go -- that way it'll work with anything that compares with 1 and that printTo knows how to convert to a string. And all checked at compile time, remember. */  getRound(n) {  var s = String(); var bottle = if (n == 1) " bottle " else " bottles "; printTo(s, n, bottle, "of beer on the wall\n", n, bottle, "of beer\n", "take one down, pass it around\n", n, bottle, "of beer on the wall!\n"); return s;  } main() {  println(join("\n", mapped(getRound, reversed(range(100)))));  } </lang> ## Chapel copied from http://99-bottles-of-beer.net/language-chapel-1215.html, with minor modifications for chapel 1.7 Works with: Chapel version 1.7.0 <lang Chapel> /*********************************************************************** * Chapel implementation of "99 bottles of beer" * * by Brad Chamberlain and Steve Deitz * 07/13/2006 in Knoxville airport while waiting for flight home from * HPLS workshop * compiles and runs with chpl compiler version 1.7.0 * for more information, contact: chapel_info@cray.com * * * Notes: * o as in all good parallel computations, boundary conditions * constitute the vast bulk of complexity in this code (invite Brad to * tell you about his zany boundary condition simplification scheme) * o uses type inference for variables, arguments * o relies on integer->string coercions * o uses named argument passing (for documentation purposes only) ***********************************************************************/  // allow executable command-line specification of number of bottles // (e.g., ./a.out -snumBottles=999999) config const numBottles = 99; const numVerses = numBottles+1; // a domain to describe the space of lyrics var LyricsSpace: domain(1) = {1..numVerses}; // array of lyrics var Lyrics: [LyricsSpace] string; // parallel computation of lyrics array [verse in LyricsSpace] Lyrics(verse) = computeLyric(verse); // as in any good parallel language, I/O to stdout is serialized. // (Note that I/O to a file could be parallelized using a parallel // prefix computation on the verse strings' lengths with file seeking) writeln(Lyrics); // HELPER FUNCTIONS: proc computeLyric(verseNum) {  var bottleNum = numBottles - (verseNum - 1); var nextBottle = (bottleNum + numVerses - 1)%numVerses; return "\n" // disguise space used to separate elements in array I/O + describeBottles(bottleNum, startOfVerse=true) + " on the wall, " + describeBottles(bottleNum) + ".\n" + computeAction(bottleNum) + describeBottles(nextBottle) + " on the wall.\n";  } proc describeBottles(bottleNum, startOfVerse:bool = false) { // NOTE: bool should not be necessary here (^^^^); working around bug  var bottleDescription = if (bottleNum) then bottleNum:string else (if startOfVerse then "N" else "n") + "o more"; return bottleDescription + " bottle" + (if (bottleNum == 1) then "" else "s") + " of beer";  } proc computeAction(bottleNum) {  return if (bottleNum == 0) then "Go to the store and buy some more, " else "Take one down and pass it around, ";  } </lang> ## Chef ## CLIPS <lang clips>(deffacts beer-bottles  (bottles 99))  (deffunction bottle-count  (?count) (switch ?count (case 0 then "No more bottles of beer") (case 1 then "1 more bottle of beer") (default (str-cat ?count " bottles of beer"))))  (defrule stanza  ?bottles <- (bottles ?count) => (retract ?bottles) (printout t (bottle-count ?count) " on the wall," crlf) (printout t (bottle-count ?count) "." crlf) (printout t "Take one down, pass it around," crlf) (printout t (bottle-count (- ?count 1)) " on the wall." crlf crlf) (if (> ?count 1) then (assert (bottles (- ?count 1)))))</lang>  ## Clojure <lang Clojure>(defn sing  [start] (doseq [n (range start 0 -1)] (printf "%d bottles of beer on the wall,  %d bottles of beer, Take one down, pass it around, %d bottles of beer on the wall.\n\n"  n n (dec n))))  (sing 99)</lang> Or, using cl-format: Translation of: Common Lisp <lang Clojure>(clojure.pprint/cl-format  true "~{~[~^~]~:*~D bottle~:P of beer on the wall~%~:*~D bottle~:P of beer  Take one down, pass it around,~%~D bottle~:P~:* of beer on the wall.~2%~}"  (range 99 0 -1))</lang>  ## COBOL Works with: OpenCOBOL version 1.1 Free form version. <lang cobol>identification division. program-id. ninety-nine. environment division. data division. working-storage section. 01 counter pic 99. 88 no-bottles-left value 0. 88 one-bottle-left value 1. 01 parts-of-counter redefines counter. 05 tens pic 9. 05 digits pic 9. 01 after-ten-words. 05 filler pic x(7) value spaces. 05 filler pic x(7) value "Twenty". 05 filler pic x(7) value "Thirty". 05 filler pic x(7) value "Forty". 05 filler pic x(7) value "Fifty". 05 filler pic x(7) value "Sixty". 05 filler pic x(7) value "Seventy". 05 filler pic x(7) value "Eighty". 05 filler pic x(7) value "Ninety". 05 filler pic x(7) value spaces. 01 after-ten-array redefines after-ten-words. 05 atens occurs 10 times pic x(7). 01 digit-words. 05 filler pic x(9) value "One". 05 filler pic x(9) value "Two". 05 filler pic x(9) value "Three". 05 filler pic x(9) value "Four". 05 filler pic x(9) value "Five". 05 filler pic x(9) value "Six". 05 filler pic x(9) value "Seven". 05 filler pic x(9) value "Eight". 05 filler pic x(9) value "Nine". 05 filler pic x(9) value "Ten". 05 filler pic x(9) value "Eleven". 05 filler pic x(9) value "Twelve". 05 filler pic x(9) value "Thirteen". 05 filler pic x(9) value "Fourteen". 05 filler pic x(9) value "Fifteen". 05 filler pic x(9) value "Sixteen". 05 filler pic x(9) value "Seventeen". 05 filler pic x(9) value "Eighteen". 05 filler pic x(9) value "Nineteen". 05 filler pic x(9) value spaces. 01 digit-array redefines digit-words. 05 adigits occurs 20 times pic x(9). 01 number-name pic x(15). procedure division. 100-main section. 100-setup. perform varying counter from 99 by -1 until no-bottles-left perform 100-show-number display " of beer on the wall" perform 100-show-number display " of beer" display "Take " with no advancing if one-bottle-left display "it " with no advancing else display "one " with no advancing end-if display "down and pass it round" subtract 1 from counter giving counter perform 100-show-number display " of beer on the wall" add 1 to counter giving counter display space end-perform. display "No more bottles of beer on the wall" display "No more bottles of beer" display "Go to the store and buy some more" display "Ninety Nine bottles of beer on the wall" stop run. 100-show-number. if no-bottles-left display "No more" with no advancing else if counter < 20 display function trim( adigits( counter ) ) with no advancing else if counter < 100 move spaces to number-name string atens( tens ) delimited by space, space delimited by size, adigits( digits ) delimited by space into number-name display function trim( number-name) with no advancing end-if end-if end-if. if one-bottle-left display " bottle" with no advancing else display " bottles" with no advancing end-if. 100-end. end-program.</lang> Another free-form version, without using DISPLAY NO ADVANCING. <lang cobol>identification division. program-id. ninety-nine. environment division. data division. working-storage section. 01 counter pic 99. 88 no-bottles-left value 0. 88 one-bottle-left value 1. 01 parts-of-counter redefines counter. 05 tens pic 9. 05 digits pic 9. 01 after-ten-words. 05 filler pic x(7) value spaces. 05 filler pic x(7) value "Twenty". 05 filler pic x(7) value "Thirty". 05 filler pic x(7) value "Forty". 05 filler pic x(7) value "Fifty". 05 filler pic x(7) value "Sixty". 05 filler pic x(7) value "Seventy". 05 filler pic x(7) value "Eighty". 05 filler pic x(7) value "Ninety". 05 filler pic x(7) value spaces. 01 after-ten-array redefines after-ten-words. 05 atens occurs 10 times pic x(7). 01 digit-words. 05 filler pic x(9) value "One". 05 filler pic x(9) value "Two". 05 filler pic x(9) value "Three". 05 filler pic x(9) value "Four". 05 filler pic x(9) value "Five". 05 filler pic x(9) value "Six". 05 filler pic x(9) value "Seven". 05 filler pic x(9) value "Eight". 05 filler pic x(9) value "Nine". 05 filler pic x(9) value "Ten". 05 filler pic x(9) value "Eleven". 05 filler pic x(9) value "Twelve". 05 filler pic x(9) value "Thirteen". 05 filler pic x(9) value "Fourteen". 05 filler pic x(9) value "Fifteen". 05 filler pic x(9) value "Sixteen". 05 filler pic x(9) value "Seventeen". 05 filler pic x(9) value "Eighteen". 05 filler pic x(9) value "Nineteen". 05 filler pic x(9) value spaces. 01 digit-array redefines digit-words. 05 adigits occurs 20 times pic x(9). 01 number-name pic x(15). 01 stringified pic x(30). 01 outline pic x(50). 01 other-numbers. 03 n pic 999. 03 r pic 999. procedure division. 100-main section. 100-setup. perform varying counter from 99 by -1 until no-bottles-left move spaces to outline perform 100-show-number string stringified delimited by "|", space, "of beer on the wall" into outline end-string display outline end-display move spaces to outline string stringified delimited by "|", space, "of beer" into outline end-string display outline end-display move spaces to outline move "Take" to outline if one-bottle-left string outline delimited by space, space, "it" delimited by size, space, "|" into outline end-string else string outline delimited by space, space, "one" delimited by size, space, "|" into outline end-string end-if string outline delimited by "|", "down and pass it round" delimited by size into outline end-string display outline end-display move spaces to outline subtract 1 from counter giving counter end-subtract perform 100-show-number string stringified delimited by "|", space, "of beer on the wall" into outline end-string display outline end-display add 1 to counter giving counter end-add display space end-display end-perform. display "No more bottles of beer on the wall" display "No more bottles of beer" display "Go to the store and buy some more" display "Ninety-Nine bottles of beer on the wall" stop run. 100-show-number. if no-bottles-left move "No more|" to stringified else if counter < 20 string function trim( adigits( counter ) ), "|" into stringified else if counter < 100 move spaces to number-name string atens( tens ) delimited by space, space delimited by size, adigits( digits ) delimited by space into number-name end-string move function trim( number-name) to stringified divide counter by 10 giving n remainder r end-divide if r not = zero inspect stringified replacing first space by "-" end-if inspect stringified replacing first space by "|" end-if end-if end-if. if one-bottle-left string stringified delimited by "|", space, "bottle|" delimited by size into stringified end-string else string stringified delimited by "|", space, "bottles|" delimited by size into stringified end-string end-if. 100-end. end-program.</lang> A more concise version that adheres to the minimum guidelines. Leading zeros are not suppressed. (OpenCOBOL - 1.1.0) <lang cobol>program-id. ninety-nine. data division. working-storage section. 01 cnt pic 99. procedure division.  perform varying cnt from 99 by -1 until cnt < 1 display cnt " bottles of beer on the wall" display cnt " bottles of beer" display "Take one down, pass it around" subtract 1 from cnt display cnt " bottles of beer on the wall" add 1 to cnt display space end-perform.</lang>  ## CoffeeScript <lang coffeescript> bottlesOfBeer = (n) ->  "#{n} bottle#{if n is 1 then else 's'} of beer"  console.log """  #{bottlesOfBeer n} on the wall #{bottlesOfBeer n} Take one down, pass it around #{bottlesOfBeer n - 1} on the wall \n""" for n in [99..1]  </lang> With completely different approach... <lang coffeescript>for j in [99..1]  x= x += [j,j-1,'\nTake one down, pass it around\n'," bottles of beer",' on the wall\n'][i] for i in [0,3,4,0,3,2,1,3,4] console.log x.replace /(1.+)s/g, '$1'


</lang>

or as a one liner...

<lang coffeescript>console.log( if (j+2)%4 then (x=Math.round j/4)+" bottle#{if x-1 then 's' else } of beer#{if (j+1)%4 then ' on the wall' else }" else "Take one down, pass it around" ) for j in [396..1]</lang>

or another completely different one liner

<lang coffeescript>((console.log if i is 2 then "Take one down, pass it around" else "#{b-!(i-1%4)} bottle#{if 4*b+i<10 and b-i then else 's'} of beer#{if i%3 then ' on the wall' else }") for i in [4..1]) for b in [99..1]</lang>

## ColdFusion

### Classic tag based CFML

<lang cfm><cfoutput>

 <cfloop index="x" from="99" to="0" step="-1">
<cfset plur = iif(x is 1,"",DE("s"))>
#x# bottle#plur# of beer on the wall
#x# bottle#plur# of beer
Take one down, pass it around
#iif(x is 1,DE("No more"),"x-1")# bottle#iif(x is 2,"",DE("s"))# of beer on the wall
</cfloop>


</cfoutput></lang> or if you prefer: (identical output, grammatically correct to the last stanza)

### CFScript

<lang cfm><cfscript>

 for (x=99; x gte 1; x--) {
plur = iif(x==1,,DE('s'));
WriteOutput("#x# bottle#plur# of beer on the wall#x# bottle#plur# of beerTake one down, pass it around#iif(x is 1,DE('No more'),'x-1')# bottle#iif(x is 2,,DE('s'))# of beer on the wall");
}


</cfscript></lang>

## D

### Simple Solution

Works with: D version 2

Based on Steward Gordon's code at: 99-bottles-of-beer.net. <lang d>import std.stdio;

void main() {

   int bottles = 99;

   while (bottles > 1) {
writeln(bottles, " bottles of beer on the wall,");
writeln(bottles, " bottles of beer.");
writeln("Take one down, pass it around,");
if (--bottles > 1) {
writeln(bottles, " bottles of beer on the wall.\n");
}
}
writeln("1 bottle of beer on the wall.\n");

   writeln("No more bottles of beer on the wall,");
writeln("no more bottles of beer.");
writeln("Go to the store and buy some more,");
writeln("99 bottles of beer on the wall.");


}</lang>

### CTFE Solution

CTFE (Compile-Time Function Execution) is a feature of D that allows for pure functions of arbitrary complexity to be completely evaluated at compile time when every parameter is known. Note that this is distinct from the template meta-programming tricks used by some other languages, and this bottles() function could just as easily be executed during run-time. The compiled result of this program simply prints the pre-generated lyrics to the song, using a standard compiler pragma directive.

<lang d>import std.stdio, std.conv;

string bottles(in size_t num) pure {

   static string bottlesRecurse(in size_t num) pure {
return num.text ~ " bottles of beer on the wall,\n"
~ num.text ~ " bottles of beer!\n"
~ "Take one down, pass it around,\n"
~ (num - 1).text ~ " bottle" ~ ((num - 1 == 1) ? "" : "s")
~ " of beer on the wall.\n\n"
~ ((num > 2)
? bottlesRecurse(num - 1)
: "1 bottle of beer on the wall,\n"
~ "1 bottle of beer!\n"
~ "Take one down, pass it around,\n"
~ "No bottles of beer on the wall!\n\n");
}

   return bottlesRecurse(num)
~ "Go to the store and buy some more...\n"
~ num.text ~ " bottles of beer on the wall!";


}

pragma(msg, 99.bottles); void main() {}</lang>

## Dart

<lang dart>main() {

 for(int x=99;x>0;x--) {
print("$x bottles of beer on the wall"); print("$x bottles of beer");
print("Take one down, pass it around");
print("${x-1} bottles of beer on the wall"); print(""); }  }</lang> ## Delphi ## Déjà Vu <lang dejavu>plural i: if = 1 i "" "s" bottles i: local :s plural i !print( to-str i " bottle"s" of beer on the wall, " to-str i " bottle"s" of beer," ) !print\ "You take one down, pass it around, " set :i -- i if i: set :s plural i !print( to-str i " bottle"s" of beer on the wall." ) bottles i else: !print "no more bottles of beer on the wall, no more bottles of beer." !print "Go to the store and buy some more, 99 bottles of beer on the wall." bottles 99</lang> ## Dylan <lang dylan>Module: bottles define method bottles (n :: <integer>)  for (n from 99 to 1 by -1) format-out("%d bottles of beer on the wall,\n" "%d bottles of beer\n" "Take one down, pass it around\n" "%d bottles of beer on the wall\n", n, n, n - 1); end  end method</lang> ## E <lang e>def bottles(n) {  return switch (n) { match ==0 { "No bottles" } match ==1 { "1 bottle" } match _ { $n bottles }
}


} for n in (1..99).descending() {



end</lang>

## ferite

copied from 99-bottles-of-beer.net.

<lang ferite>uses "console";

number bottles = 99; boolean looping = true; object counter = closure { if (--bottles > 0) { return true; } else { return false; } };

while (looping) { Console.println("${bottles} bottles of beer on the wall,"); Console.println("${bottles} bottles of beer,"); Console.println("Take one down, pass it around,");

looping = counter.invoke();

Console.println("${bottles} bottles of beer on the wall.");</lang> ## Fexl <lang fexl> \suffix=(\n eq n 1 "" "s") \sing_count=(\n put n put " " put "bottle" put (suffix n) put " of beer") \sing_line1=(\n sing_count n put " on the wall" nl) \sing_line2=(\n sing_count n nl) \sing=  (@\loop\n le n 0 (); sing_line1 n sing_line2 n say "Take one down, pass it around" \n=(- n 1) sing_line1 n nl loop n )  sing 3 </lang> Output: 3 bottles of beer on the wall 3 bottles of beer Take one down, pass it around 2 bottles of beer on the wall 2 bottles of beer on the wall 2 bottles of beer Take one down, pass it around 1 bottle of beer on the wall 1 bottle of beer on the wall 1 bottle of beer Take one down, pass it around 0 bottles of beer on the wall  ## Forth <lang forth>:noname dup . ." bottles" ; noname ." 1 bottle" ; noname ." no more bottles" ; create bottles , , , .bottles dup 2 min cells bottles + @ execute ; .beer .bottles ." of beer" ; .wall .beer ." on the wall" ; .take ." Take one down, pass it around" ; .verse .wall cr .beer cr  1- .take cr .wall cr ;  verses begin cr .verse ?dup 0= until ; 99 verses</lang> ## Fortran <lang fortran>program bottlestest  implicit none   integer :: i character(len=*), parameter :: bwall = " on the wall", & bottles = "bottles of beer", & bottle = "bottle of beer", & take = "Take one down, pass it around", & form = "(I0, ' ', A)"   do i = 99,0,-1 if ( i /= 1 ) then write (*,form) i, bottles // bwall if ( i > 0 ) write (*,form) i, bottles else write (*,form) i, bottle // bwall write (*,form) i, bottle end if if ( i > 0 ) write (*,*) take end do  end program bottlestest</lang> ### MPI version <lang fortran>program bottlesMPI  implicit none   integer :: ierr,rank,nproc character(len=*), parameter :: bwall = " on the wall", & bottles = "bottles of beer", & bottle = "bottle of beer", & take = "Take one down, pass it around", & form = "(I0, ' ', A)"   call mpi_init(ierr) call mpi_comm_size(MPI_COMM_WORLD,nproc, ierr) call mpi_comm_rank(MPI_COMM_WORLD,rank,ierr)   if ( rank /= 1 ) then write (*,form) rank, bottles // bwall if ( rank > 0 ) write (*,form) rank, bottles else write (*,form) rank, bottle // bwall write (*,form) rank, bottle end if if ( rank > 0 ) write (*,*) take   call mpi_finalize(ierr)  end program bottlesMPI</lang> Usage: mpif90 filename.f90 mpiexec -np 99 a.out ## Frege Translation of: Haskell (identical to the Haskell, apart from adding the module declaration) Works with: Frege version 3.21.586-g026e8d7 <lang frege>module Beer where main = mapM_ (putStrLn . beer) [99, 98 .. 0] beer 1 = "1 bottle of beer on the wall\n1 bottle of beer\nTake one down, pass it around" beer 0 = "better go to the store and buy some more." beer v = show v ++ " bottles of beer on the wall\n"  ++ show v ++ " bottles of beer\nTake one down, pass it around\n" ++ head (lines$ beer $v-1) ++ "\n"</lang>  ## friendly interactive shell ## Frink Frink tracks units of measure through all calculations. It has a large library of built-in units of measure, including volume. The following program prints out the remaining volume of beer (assuming we start with 99 bottles of beer, each containing 12 fluid ounces) in different random units of volume, never repeating a unit. <lang frink> units = array[units[volume]] showApproximations[false] for n = 99 to 0 step -1 {  unit = units.removeRandom[] str = getBottleString[n, unit] println["$str of beer on the wall, $str."]   if (n == 0) println["Go to the store and buy some more, 99 bottles of beer on the wall."] else println["Take one down and pass it around, " + getBottleString[n-1, unit] + " on the wall.\n"]  } getBottleString[n, unit] := format[n*12 floz, unit, 6] + "s" </lang> Sample randomized output: 0.019386 facecords of beer on the wall, 0.019386 facecords. Take one down and pass it around, 0.019190 facecords on the wall. 36.750000 quarts of beer on the wall, 36.750000 quarts. Take one down and pass it around, 36.375000 quarts on the wall. 581539.650545 brminims of beer on the wall, 581539.650545 brminims. Take one down and pass it around, 575544.396416 brminims on the wall. 10.377148 scotsoatlippys of beer on the wall, 10.377148 scotsoatlippys. Take one down and pass it around, 10.269053 scotsoatlippys on the wall. 7.416004 cangallons of beer on the wall, 7.416004 cangallons. Take one down and pass it around, 7.337941 cangallons on the wall. 3335.894135 dessertspoons of beer on the wall, 3335.894135 dessertspoons. Take one down and pass it around, 3300.405899 dessertspoons on the wall. 0.233105 barrelbulks of beer on the wall, 0.233105 barrelbulks. Take one down and pass it around, 0.230599 barrelbulks on the wall. 21.766118 magnums of beer on the wall, 21.766118 magnums. Take one down and pass it around, 21.529530 magnums on the wall. 1092.000000 fluidounces of beer on the wall, 1092.000000 fluidounces. Take one down and pass it around, 1080.000000 fluidounces on the wall. ... 12.000000 ponys of beer on the wall, 12.000000 ponys. Take one down and pass it around, 0.000000 ponys on the wall. 0.000000 brfluidounces of beer on the wall, 0.000000 brfluidounces. Go to the store and buy some more, 99 bottles of beer on the wall.  ## FunL <lang funl>val  numbers = {1:'one', 2:'two', 3:'three', 4:'four', 5:'five', 6:'six', 7:'seven', 8:'eight', 9:'nine', 10:'ten', 11:'eleven', 12:'twelve'} alt = {3:'thir', 5:'fif'}  def  suffix( a, b ) = (if a.endsWith( 't' ) then a.substring( 0, a.length()-1 ) else a) + b   number( n@(13 | 15) ) = suffix( alt(n%10), 'teen' ) number( 20 ) = 'twenty' number( n@(30 | 50) ) = suffix( alt(n\10), 'ty' ) number( n ) | n <= 12 = numbers(n) | n <= 19 = suffix( numbers(n%10), 'teen' ) | 10|n = suffix( numbers(n\10), 'ty' ) | otherwise = number( n\10*10 ) + '-' + number( n%10 )   cap( s ) = s.substring( 0, 1 ).toUpperCase() + s.substring( 1, s.length() )   bottles( 0 ) = 'no more bottles' bottles( 1 ) = 'one bottle' bottles( n ) = number( n ) + ' bottles'   verse( 0 ) = ('No more bottles of beer on the wall, no more bottles of beer.\n' + 'Go to the store and buy some more, ninety-nine bottles of beer on the wall.') verse( n ) = (cap( bottles(n) ) + ' of beer on the wall, ' + bottles( n ) + ' of beer.\n' + 'Take one down and pass it around, ' + bottles( n-1 ) + ' of beer on the wall.\n')  for i <- 99..0 by -1 do println( verse(i) )</lang> ## GAP <lang gap>Bottles := function(n) local line, i, j, u; line := function(n) s := String(n); if n < 2 then return Concatenation(String(n), " bottle of beer"); else return Concatenation(String(n), " bottles of beer"); fi; end; for i in [1 .. n] do j := n - i + 1; u := line(j); Display(Concatenation(u, " on the wall")); Display(u); Display("Take one down, pass it around"); Display(Concatenation(line(j - 1), " on the wall")); if i <> n then Display(""); fi; od; end;</lang> ## gnuplot <lang gnuplot>if (!exists("bottles")) bottles = 99 print sprintf("%i bottles of beer on the wall", bottles) print sprintf("%i bottles of beer", bottles) print "Take one down, pass it around" bottles = bottles - 1 print sprintf("%i bottles of beer on the wall", bottles) print "" if (bottles > 0) reread</lang> ## Go ### No sense of humor <lang go>package main import "fmt" func main() { cardinality := func (i int) string { if i!=1 { return "s" } return "" } for i := 99; i > 0; i-- { fmt.Printf("%d bottle%s of beer on the wall\n", i, cardinality(i)) fmt.Printf("%d bottle%s of beer\n", i, cardinality(i)) fmt.Printf("Take one down, pass it around\n") fmt.Printf("%d bottle%s of beer on the wall\n", i-1, cardinality(i-1)) } }</lang> ### Typoglycemic With code from RC tasks Number names, Knuth shuffle. <lang go>package main import (  "fmt" "math/rand" "strings" "time"  ) func main() {  rand.Seed(time.Now().UnixNano()) for i := 99; i > 0; i-- { fmt.Printf("%s %s %s\n", slur(numberName(i), i), pluralizeFirst(slur("bottle of", i), i), slur("beer on the wall", i)) fmt.Printf("%s %s %s\n", slur(numberName(i), i), pluralizeFirst(slur("bottle of", i), i), slur("beer", i)) fmt.Printf("%s %s %s\n", slur("take one", i), slur("down", i), slur("pass it around", i)) fmt.Printf("%s %s %s\n", slur(numberName(i-1), i), pluralizeFirst(slur("bottle of", i), i-1), slur("beer on the wall", i)) }  } // adapted from Number names task func numberName(n int) string {  switch { case n < 0: case n < 20: return small[n] case n < 100: t := tens[n/10] s := n % 10 if s > 0 { t += " " + small[s] } return t } return ""  } var small = []string{"no", "one", "two", "three", "four", "five", "six",  "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen"}  var tens = []string{"ones", "ten", "twenty", "thirty", "forty",  "fifty", "sixty", "seventy", "eighty", "ninety"}  // pluralize first word of s by adding an s, but only if n is not 1. func pluralizeFirst(s string, n int) string {  if n == 1 { return s } w := strings.Fields(s) w[0] += "s" return strings.Join(w, " ")  } // p is string to slur, d is drunkenness, from 0 to 99 func slur(p string, d int) string {  // shuffle only interior letters a := []byte(p[1 : len(p)-1]) // adapted from Knuth shuffle task. // shuffle letters with probability d/100. for i := len(a) - 1; i >= 1; i-- { if rand.Intn(100) >= d { j := rand.Intn(i + 1) a[i], a[j] = a[j], a[i] } } // condense spaces w := strings.Fields(p[:1] + string(a) + p[len(p)-1:]) return strings.Join(w, " ")  }</lang> Output: Things start out pretty well... ninety nine bottles of beer on the wall ninety nine bottles of beer take one down pass it around ninety eight bottles of beer on the wall ninety eight bottles of beer on the wall ninety eight bottles of beer take one down pass it around ninety seven bottles of beer on the wall ninety seven boetlts of beer on the wall ninety seven bottles of beer take one down pass it around ninety six botelts of beer on the wall  Soon, eighty four bottles of bere wn the oall ehigty four bottles of beer tkae one down pnssti arouad eihhty tgree bttoles of beer en tho wall eighty three blottes of beet on rhe wall eighty three bottles of beer taen oke down pass it around eiwyth tgo bttoles of beew on lhr eatl  It ends very well, if you're drinking along. two btloots ef bre enehta wo ll two bs tleootf beer tnoeka e dwon pts ou nsaaird one bolote tf betwr le ao enhl one beoo ttlf blwtenr ehoa el one bltooe tf beer tne okae down pasaostiu rnd no bletts oof beloethw r ea nl  ## Go! Copied from The 99 Bottles of Beer web site with a minor bug fix. <lang go!>-- -- 99 Bottles of Beer in Go! -- John Knottenbelt -- -- Go! is a multi-paradigm programming language that is oriented -- to the needs of programming secure, production quality, agent -- based applications. -- -- http://www.doc.ic.ac.uk/~klc/dalt03.html -- main .. {  include "sys:go/io.gof". include "sys:go/stdlib.gof".   main() -> drink(99); stdout.outLine("Time to buy some more beer...").   drink(0) -> {}. drink(i) -> stdout.outLine( bottles(i) <> " on the wall,\n" <> bottles(i) <> ".\n" <> "take one down, pass it around,\n" <> bottles(i-1) <> " on the wall.\n"); drink(i-1).   bottles(0) => "no bottles of beer". bottles(1) => "1 bottle of beer". bottles(i) => i^0 <> " bottles of beer".  }</lang> ## Gosu <lang gosu> for (i in 99..0) {  print("${i} bottles of beer on the wall")

   if (i > 0) {

## Groovy

### Basic Solution

With a closure to handle special cardinalities of bottles. <lang groovy>def bottles = { "${it==0 ? 'No more' : it} bottle${it==1 ?  : 's' }" }

99.downto(1) { i ->

   print """


"${m?' on the wall':'\nTake one down, pass it around'}\n"  }</lang> ### Bottomless Beer Solution Using more closures to create a richer lyrical experience. <lang groovy>def bottles = { "${it==0 ? 'No more' : it} bottle${it==1 ? : 's' }" } def initialState = {  """${result(it)}


${resultShort(it)}""" } def act = {  it > 0 ? "Take${it==1 ? 'it' : 'one'} down, pass it around" :
"Go to the store, buy some more"


}

def delta = { it > 0 ? -1 : 99 }

def resultShort = { "${bottles(it)} of beer" } def result = { "${resultShort(it)} on the wall" }

// //// uncomment commented lines to create endless drunken binge //// // // while (true) { 99.downto(0) { i ->

 print """


${initialState(i)}${act(i)} ${result(i+delta(i))} """ } // Thread.sleep(1000) // }</lang> ## GUISS We will just use the calculator and keep taking one off. We do not get the full text here, but the number of the calculator shows how many bottles we still have left to drink: <lang guiss>Start,Programs,Accessories,Calculator,Button:9,Button:9, Button:[hyphen],Button:1,Button:[equals],Button:[hyphen],Button:1,Button:[equals], Button:[hyphen],Button:1,Button:[equals],Button:[hyphen],Button:1,Button:[equals], Button:[hyphen],Button:1,Button:[equals],Button:[hyphen],Button:1,Button:[equals], Button:[hyphen],Button:1,Button:[equals],Button:[hyphen],Button:1,Button:[equals] </lang> We haven't drank all of the bottles at this point, but we can keep going, if we want. ## Haskell A relatively concise solution: <lang haskell>main = mapM_ (putStrLn . beer) [99, 98 .. 0] beer 1 = "1 bottle of beer on the wall\n1 bottle of beer\nTake one down, pass it around" beer 0 = "better go to the store and buy some more." beer v = show v ++ " bottles of beer on the wall\n"  ++ show v ++" bottles of beer\nTake one down, pass it around\n" ++ head (lines$ beer $v-1) ++ "\n"</lang>  As a list comprehension: <lang haskell>import qualified Char main = putStr$ concat

  [up (bob n) ++ wall ++ ", " ++ bob n ++ ".\n" ++
pass n ++ bob (n - 1) ++ wall ++ ".\n\n" |
n <- [99, 98 .. 0]]
where bob n = (num n) ++ " bottle" ++ (s n) ++ " of beer"
wall = " on the wall"
pass 0 = "Go to the store and buy some more, "
pass _ = "Take one down and pass it around, "
up (x : xs) = Char.toUpper x : xs
num (-1) = "99"
num 0    = "no more"
num n    = show n
s 1 = ""
s _ = "s"</lang>


Another version, which uses a Writer monad to collect each part of the song. It also uses Template Haskell to generate the song at compile time.

-- This is calculated at compile time, and is equivalent to -- songString = "99 bottles of beer on the wall\n99 bottles..." songString =

   $(let sing = tell -- we can't sing very well...   someBottles 1 = "1 bottle of beer " someBottles n = show n ++ " bottles of beer "   bottlesOfBeer n = (someBottles n ++)   verse n = do sing$ n bottlesOfBeer "on the wall\n"
sing $n bottlesOfBeer "\n" sing$ "Take one down, pass it around\n"
sing $(n - 1) bottlesOfBeer "on the wall\n\n"   song = execWriter$ mapM_ verse [99,98..1]

     in return $LitE$ StringL $song)  main = putStr songString</lang> ## Haxe ### Simple solution <lang haxe>class RosettaDemo {  static public function main() { singBottlesOfBeer(100); }   static function singBottlesOfBeer(bottles : Int) { var plural : String = 's';   while (bottles >= 1) { Sys.println(bottles + " bottle" + plural + " of beer on the wall,"); Sys.println(bottles + " bottle" + plural + " of beer!"); Sys.println("Take one down, pass it around,"); if (bottles - 1 == 1) { plural = ; }   if (bottles > 1) { Sys.println(bottles-1 + " bottle" + plural + " of beer on the wall!\n"); } else { Sys.println("No more bottles of beer on the wall!"); } bottles--; } }  }</lang> ### Macro solution All those counters, loops and conditinal blocks are pretty expensive in runtime compared to single print of fully inlined text of the song. Let's generate that print with macro. <lang haxe>class Bottles {  static public function main () : Void { singBottlesOfBeer(100); }   macro static public function singBottlesOfBeer (bottles:Int) { var lines = []; var s : String = 's';   var song : String = ; while( bottles >= 1 ){ song += '$bottles bottle$s of beer on the wall,\n'; song += '$bottles bottle$s of beer!\n'; song += 'Take one down, pass it around,\n';   bottles --;   if( bottles > 1 ){ song += '$bottles bottles of beer on the wall!\n\n';
}else if( bottles == 1 ){
s = ;
song += '$bottles bottle of beer on the wall!\n\n'; }else{ song += 'No more bottles of beer on the wall!\n'; } }   return macro Sys.print($v{song});
}


}</lang>

## HicEst

<lang hicest>DO x = 99, 1, -1

 WRITE()   x       , "bottles of beer on the wall"
BEEP("T16 be be be   bH bH   bH be   be be  2be ")

 WRITE()   x       , "bottles of beer"
BEEP("2p  f f f      c  c    c  2f  ")

 WRITE()  "take one down,  pass it around"
BEEP("2p  2d   d   d   2p d    d  d 2d  ")

 WRITE()   x     , "bottles of beer on the wall"
BEEP("2p  #A #A #A c  c    d  #d   #d #d  2#d 2p")


ENDDO</lang>

## Icon and Unicon

The default is 99 bottles, but you can change this on the command line for really long trips... <lang icon>procedure main(args)

  numBeers := integer(args[1]) | 99
drinkUp(numBeers)


end

procedure drinkUp(beerMax)

   static beerMap
initial {
beerMap := table(" bottles")
beerMap[1] := " bottle"
}

   every beerCount := beerMax to 1 by -1 do {
writes( beerCount,beerMap[beerCount]," of beer on the wall, ")
write(  beerCount,beerMap[beerCount]," of beer.")

      writes("Take one down and pass it around, ")
write(case x := beerCount-1 of {
0       : "no more bottles"
default : x||beerMap[x]
}," of beer on the wall.\n")
}

   write("No more bottles of beer on the wall, no more bottles of beer.")
write("Go to the store and buy some more, ",
beerMax," bottles of beer on the wall.")


end</lang>

## IDL

<lang IDL>Pro bottles

for i=1,99 do begin

print, 100-i, " bottles of beer on the wall.", 100-i, $" bottles of beer.", " Take one down, pass it around," ,$
99-i, " bottles of beer on the wall."


endfor End

</lang>

Since in IDL "FOR"-loops are the embodiment of pure evil (see http://www.idlcoyote.com/tips/forloops.html and http://www.idlcoyote.com/tips/forloops2.html) there is also a loop free IDL way:

<lang IDL>Pro bottles_noloop

   b=(reverse(shift(sindgen(100),-1)))[1:99]
b2=reverse(sindgen(99))
wallT=replicate(' bottles of beer on the wall.', 100)
wallT2=replicate(' bottles of beer.', 100)
takeT=replicate('Take one down, pass it around,', 100)
print, b+wallT+string(10B)+b+wallT2+string(10B)+takeT+string(10B)+b2+wallT+string(10B)


End</lang>

## Idris

<lang Idris> beerSong : Fin 100 -> String beerSong x = verses x where

   bottlesOfBeer : Fin n -> String
bottlesOfBeer fZ      = "No more bottles of beer"
bottlesOfBeer (fS fZ) = "1 bottle of beer"
bottlesOfBeer k       = (show (finToInteger k)) ++ " bottles of beer"

   verse : Fin n -> String
verse fZ     = ""
verse (fS n) =
(bottlesOfBeer (fS n)) ++ " on the wall,\n" ++
(bottlesOfBeer (fS n)) ++ "\n" ++
"Take one down, pass it around\n" ++
(bottlesOfBeer n) ++ " on the wall\n"

   verses : Fin n -> String
verses fZ     = ""
verses (fS n) = (verse (fS n)) ++ (verses n)


</lang>

## Inform 6

<lang inform6>[ Bottles i;

 if(i == 1) return "bottle";

 return "bottles";


];

[ Beer i;

 print i, " ", (string) Bottles(i), " of beer on the wall^";
print i, " ", (string) Bottles(i), " of beer^";
print "Take one down, pass it around^";
i--;
print i, " ", (string) Bottles(i), " of beer on the wall^^";

 if(i ~= 0) Beer(i);


];

[ Main;

 Beer(99);


]; </lang>

## Inform 7

### Programmatic solution

<lang inform7>Beer Hall is a room.

When play begins: repeat with iteration running from 1 to 99: let N be 100 - iteration; say "[N] bottle[s] of beer on the wall[line break]"; say "[N] bottle[s] of beer[line break]"; say "Take one down, pass it around[line break]"; say "[N - 1] bottle[s] of beer on the wall[paragraph break]"; end the story.</lang>

### World model solution

This solution uses in-game objects to represent the wall and the bottles.

<lang inform7>Beer Hall is a room.

The plural of bottle of beer is bottles of beer. A bottle of beer is a kind of thing.

The wall is a scenery supporter in Beer Hall. 99 bottles of beer are on the wall.

When play begins: while something is on the wall: say "[what's on the wall] on the wall[line break]"; say "[what's on the wall][line break]"; say "Take one down, pass it around[line break]"; remove a random thing on the wall from play; say "[what's on the wall] on the wall[paragraph break]"; end the story.

To say what's on the wall: if more than one thing is on the wall, say list of things on the wall; otherwise say "[number of things on the wall in words] bottle[s] of beer".</lang>

## Io

<lang io>bottles := method(i,

   if(i==0, return "no more bottles of beer")
if(i==1, return "1 bottle of beer")
"" .. i .. " bottles of beer"


) for(i, 99, 1, -1,

   write(
bottles(i), " on the wall, ",
bottles(i), ",\n",
"take one down, pass it around,\n",
bottles(i - 1), " on the wall.\n\n"
)


)</lang>

## Ioke

<lang ioke>bottle = method(i,

 case(i,
0, "no more bottles of beer",
1, "1 bottle of beer",
"#{i} bottles of beer"))


(99..1) each(i,

 "#{bottle(i)} on the wall, " println
"take one down, pass it around," println
"#{bottle(i - 1)} on the wall.\n" println


)</lang>

## J

As posted at the J wiki <lang j>bob =: ": , ' bottle' , (1 = ]) }. 's of beer'"_ bobw=: bob , ' on the wall'"_ beer=: bobw , ', ' , bob , '; take one down and pass it around, ' , bobw@<: beer"0 >:i.-99</lang>

Output:
99 bottles of beer on the wall, 99 bottles of beer; take one down and pass it around, 98 bottles of beer on the wall
98 bottles of beer on the wall, 98 bottles of beer; take one down and pass it around, 97 bottles of beer on the wall
...
3 bottles of beer on the wall, 3 bottles of beer; take one down and pass it around, 2 bottles of beer on the wall
2 bottles of beer on the wall, 2 bottles of beer; take one down and pass it around, 1 bottle of beer on the wall
1 bottle of beer on the wall, 1 bottle of beer; take one down and pass it around, 0 bottles of beer on the wall 

## Java

### Console

MessageFormat's choice operator is used to properly format plurals. <lang java>import java.text.MessageFormat; public class Beer {

static String bottles(final int n)
{
return MessageFormat.format("{0,choice,0#No more bottles|1#One bottle|2#{0} bottles} of beer", n);
}
public static void main(final String[] args)
{
String byob = bottles(99);
for (int x = 99; x > 0;)
{
System.out.println(byob + " on the wall");
System.out.println(byob);
System.out.println("Take one down, pass it around");
byob = bottles(--x);
System.out.println(byob + " on the wall\n");
}
}


}</lang>

Optimized <lang java>public class Beer {

public static void main(final String[] args)
{
int beer = 99;
StringBuilder sb = new StringBuilder();
String data[] = new String[] { " bottles of beer on the wall\n",
" bottles of beer.\nTake one down, pass it around,\n",
"Better go to the store and buy some more." };

 while (beer > 0)
sb.append(beer).append(data[0]).append(beer).append(data[1]).append(--beer).append(data[0]).append("\n");

 System.out.println(sb.append(data[2]).toString());
}


}</lang>

Recursive <lang java>public class Beer { public static void main(String args[]) { song(99); }

public static void song(int b) { if(b>=0) { if(b>1) System.out.println(b+" bottles of beer on the wall\n"+b+" bottles of beer\nTake one down, pass it around\n"+(b-1)+" bottles of beer on the wall.\n"); else if(b==1) System.out.println(b+" bottle of beer on the wall\n"+b+" bottle of beer\nTake one down, pass it around\n"+(b-1)+" bottles of beer on the wall.\n"); else System.out.println(b+" bottles of beer on the wall\n"+b+" bottles of beer\nBetter go to the store and buy some more!"); song(b-1); } } }</lang>

### An object-oriented solution

Translation of: C++

### GUI

Library: Swing
Library: AWT

This version requires user interaction. The first two lines are shown in a text area on a window. The third line is shown on a button which you need to click to see the fourth line in a message box. The numbers update and the process repeats until "0 bottles of beer on the wall" is shown in a message box, when the program ends. <lang java>import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JOptionPane; import javax.swing.JTextArea; public class Beer extends JFrame implements ActionListener{

       private int x;
private JButton take;
private JTextArea text;
public static void main(String[] args){
new Beer();//build and show the GUI
}

       public Beer(){
x= 99;
take= new JButton("Take one down, pass it around");
text= new JTextArea(4,30);//size the area to 4 lines, 30 chars each
text.setText(x + " bottles of beer on the wall\n" + x + " bottles of beer");
text.setEditable(false);//so they can't change the text after it's displayed
setLayout(new BorderLayout());//handle placement of components
add(text, BorderLayout.CENTER);//put the text area in the largest section
add(take, BorderLayout.SOUTH);//put the button underneath it
pack();//auto-size the window
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//exit on "X" (I hate System.exit...)
setVisible(true);//show it
}

       public void actionPerformed(ActionEvent arg0){
if(arg0.getSource() == take){//if they clicked the button
JOptionPane.showMessageDialog(null, --x + " bottles of beer on the wall");//show a popup message
text.setText(x + " bottles of beer on the wall\n" + x + " bottles of beer");//change the text
}
if(x == 0){//if it's the end
dispose();//end
}
}


}</lang>

## JavaScript

### ES3-5

<lang javascript>var beer = 99; while (beer > 0) {

 var verse = [
beer + " bottles of beer on the wall,",
beer + " bottles of beer!",
"Take one down, pass it around",
(beer - 1) + " bottles of beer on the wall!"
].join("\n");

 console.log(verse);

 beer--;


} </lang>

### ES6

<lang javascript>let beer = 99; while (beer > 0) {

 let verse = ${beer} bottles of beer on the wall,${beer} bottles of beer!
Take one down, pass it around

<lang seed7>$include "seed7_05.s7i"; const proc: main is func  local var integer: number is 0; begin for number range 99 downto 2 do write( number <& " bottles of beer on the wall, "); writeln( number <& " bottles of beer."); write( "Take one down and pass it around, "); writeln( pred(number) <& " bottles of beer on the wall."); writeln; end for; writeln("1 bottle of beer on the wall, 1 bottle of beer."); writeln("Take one down and pass it around, no more bottles of beer on the wall."); writeln; writeln("No more bottles of beer on the wall, no more bottles of beer."); writeln("Go to the store and buy some more, 99 bottles of beer on the wall.") end func;</lang>  ## Shiny <lang shiny>for 99 i:99-a  s: if i > 1 's' end   if i > 0 and i < 99 switch if i = 6 say "A six-pack on the wall!\n" break if i = 24 say "A carton on the wall!\n" break say "$i bottle$s of beer on the wall!\n" ends   say "$i bottle$s of beer on the wall," say "$i bottle\$s of beer!"
say "Take one down, pass it around!"


end say "Aww...no more bottles of beer on the wall... it must be your shout :)"</lang>

## Sidef

<lang ruby>99.downto(0).each { |i|

   var bottles = "#{i == 0 ? 'No' : i} bottle#{i == 1 ?  : 's'}";
var sentence = "#{bottles} of beer on the wall" -> say;
i > 0 && (
sentence.substr(0, bottles.length + 8).say;
"Take one down, pass it around\n".say;
);


};</lang>

Simpler: <lang ruby>99.downto(2).each { | n |

 say "#{n} bottles of beer on the wall, #{n} bottles of beer!";
say "Take one down, pass it around, #{n - 1} bottle#{n > 2 ? 's' : } of beer on the wall.\n";


};

say "One bottle of beer on the wall, one bottle of beer!"; say "Take one down, pass it around, no more bottles of beer on the wall.";</lang>

## Slate

<lang slate>n@(Integer traits) bottleVerse [| nprinted |

 nprinted: n printString ; ' bottle' ; (n > 1 ifTrue: ['s'] ifFalse: []) ; ' of beer'.
inform: nprinted ; ' on the wall.'.
inform: nprinted.
inform: 'Take one down, pass it around.'.
inform: nprinted ; ' on the wall.'.


].

x@(Integer traits) bottles [

 x downTo: 0 do: #bottleVerse er


].

99 bottles.</lang>

## Smalltalk

A straightforward approach: <lang smalltalk>Smalltalk at: #sr put: 0 ; at: #s put: 0 ! sr := Dictionary new. sr at: 0 put: ' bottle' ;

  at: 1 put: ' bottles' ;
at: 2 put: ' of beer' ;
at: 3 put: ' on the wall' ;
at: 4 put: 'Take one down, pass it around' !


99 to: 0 by: -1 do: [:v | v print.

        ( v == 1 ) ifTrue: [ s := 0. ]


ifFalse: [ s := 1. ]. Transcript show: (sr at:s) ; show: (sr at:2) ; show: (sr at:3) ; cr. v print. Transcript show: (sr at:s) ; show: (sr at:2) ; cr. (v ~~ 0) ifTrue: [ Transcript show: (sr at:4) ; cr. ].

  ].</lang>


## SNOBOL4

<lang snobol> x = 99 again output = X " bottles of beer on the wall" output = X " bottles of beer" ?eq(X,0) :s(zero) output = "Take one down, pass it around" output = (X = gt(x,0) X - 1) " bottle of beer on the wall..." :s(again) zero output = "Go to store, get some more" output = "99 bottles of beer on the wall" end</lang>

### Function

Works with: Macro Spitbol
Works with: CSnobol

Function version with string composition. Function returns one verse for x bottles. Correctly handles bottle/bottles. <lang SNOBOL4> define('bottles(x)')

       nl = char(13) char(10) ;* Win/DOS, change as needed
s2 = ' of beer'; s3 = ' on the wall'
s4 = 'Take one down, pass it around'
s5 = 'Go to the store, get some more' :(bottles_end)


bottles s1 = (s1 = ' Bottle') ne(x,1) 's'

       output = nl x s1 s2 s3 nl x s1 s2
x = gt(x,0) x - 1 :f(done)
s1 = (s1 = ' Bottle') ne(x,1) 's'
output = s4 nl x s1 s2 s3 :(return)


done output = s5 nl 99 s1 s2 s3 :(return) bottles_end

• # Test and display, only 2 bottles!
       n = 2


loop bottles(n); n = gt(n,0) n - 1 :s(loop) end</lang>

Output:

2 Bottles of beer on the wall
2 Bottles of beer
Take one down, pass it around
1 Bottle of beer on the wall

1 Bottle of beer on the wall
1 Bottle of beer
Take one down, pass it around
0 Bottles of beer on the wall

0 Bottles of beer on the wall
0 Bottles of beer
Go to the store, get some more
99 Bottles of beer on the wall

## Sparkling

<lang sparkling>var bottles = 99;

do {

   printf("%u bottles of beer on the wall\n", bottles);
printf("%u bottles of beer\n", bottles);
printf("Take one down, pass it around\n");
printf("%u bottles of beer on the wall\n\n", --bottles);


} while(bottles > 1);

printf("1 bottle of beer on the wall\n1 bottle of beer\nTake it down, pass it around\n0 bottles of beer on the wall\n");</lang>

## SQL

<lang SQL> select

       ( 100 - level ) || ' bottle' || case 100 - level when 1 then  else 's' end || ' of beer on the wall'
|| chr(10)
|| ( 100 - level ) || ' bottle' || case 100 - level when 1 then  else 's' end || ' of beer'
|| chr(10)
|| 'Take one down, pass it around'
|| chr(10)
|| ( 99 - level ) || ' bottle' || case 99 - level when 1 then  else 's' end || ' of beer on the wall'
from dual connect by level <= 99;


</lang>

<lang SQL>

DELIMITER $$DROP PROCEDURE IF EXISTS bottles_$$ CREATE pROCEDURE bottles_(inout bottle_count int, inout song text) BEGIN declare bottles_text varchar(30);

IF bottle_count > 0 THEN

   if bottle_count != 1 then
set bottles_text :=  ' bottles of beer ';
else set bottles_text = ' bottle of beer ';
end if;

SELECT concat(song, bottle_count, bottles_text, ' \n') INTO song;
SELECT concat(song, bottle_count, bottles_text,  'on the wall\n') INTO song;
SELECT concat(song, 'Take one down, pass it around\n') into song;
SELECT concat(song, bottle_count -1 , bottles_text,  'on the wall\n\n') INTO song;
set bottle_count := bottle_count -1;
CALL bottles_( bottle_count, song);
END IF;


## TXR

The (range 99 -1 -1) expression produces a lazy list of integers from 99 down to -1. The mapcar* function lazily maps these numbers to strings, and the rest of the code treats this lazy list as text stream to process, extracting the numbers with some pattern matching cases and interpolating them into the song's text. Functional programming with lazy semantics meets text processing, pattern matching and here documents.

<lang txr>@(next :list @(mapcar* (fun tostring) (range 99 -1 -1))) @(collect) @number @ (trailer) @number_less_1 @ (cases) @ (bind number "1") @ (output) 1 bottle of beer one the wall 1 bottle of beer @ (end) @ (or) @ (output) @number bottles of beer one the wall @number bottles of beer @ (end) @ (end) @ (cases) @ (bind number "0") @ (output) Go to the store and get some more, 99 bottles of beer on the wall!

@ (end) @ (or) @ (output) Take one down and pass it around @number_less_1 bottles of beer on the wall

@ (end) @ (end) @(end)</lang>

To make the song repeat indefinitely, change the first line to:

<lang txr>@(next :list @(mapcar* (fun tostring) (repeat (range 99 0 -1))))</lang>

Now it's processing an infinite lazy lists consisting of repetitions of the integer sequences 99 98 ... 0.

## Ursala

<lang Ursala>#import nat

1. each function takes a natural number to a block of text

quantity = # forms the plural as needed

~&iNC+ --' of beer'+ ~&?(

  1?=/'1 bottle'! --' bottles'+ ~&h+ %nP,
'no more bottles'!)


verse =

^(successor,~&); ("s","n"). -[

  -[quantity "s"]- on the wall, -[quantity "s"]-,
Take one down and pass it around, -[quantity "n"]- on the wall.]-


refrain "n" =

-[

  No more bottles of beer on the wall, -[quantity 0]-.
Go to the store and buy some more, -[quantity "n"]- on the wall.]-


whole_song "n" = ~&ittt2BSSL (verse*x iota "n")--<refrain "n">

1. show+

main = whole_song 99</lang>

## V

<lang v>[bottles

 [newline '' puts].
[beer
[0 =] ['No more bottles of beer' put] if
[1 =] ['One bottle of beer' put] if
[1 >] [dup put ' bottles of beer' put] if].
[0 =] [newline]
[beer ' on the wall, ' put beer newline
'Take one down and pass it around, ' put pred beer ' on the wall' puts newline]
tailrec].


99 bottles</lang>

## Vala

<lang vala>void main() {

   uint bottles = 99;
do {
print("%u bottles of beer on the wall.\n", bottles);
print("%u bottles of beer!\n", bottles);
print("Take one down, pass it around!\n");
--bottles;
if (bottles == 0) {
print("No bottles");
}
else if (bottles == 1) {
print("1 bottle");
}
else {
print("%u bottles", bottles);
}
print(" of beer on the wall!\n\n");
} while (bottles != 0);


}</lang>

## Vox

<lang vox> // translated from <http://rosettacode.org/wiki/99_Bottles_of_Beer#JavaScript>

local beer; while((beer = typeof beer == "null" ? 99 : beer) > 0)

   println(
beer + " bottle" +
(beer != 1 ? "s" : "") +
" of beer on the wall\n" + beer + " bottle" +
(beer != 1 ? "s" : "") +
" of beer\nTake one down, pass it around\n" +
(--beer) + " bottle" +
(beer != 1 ? "s" : "") + " of beer on the wall\n"
);


</lang>

## Wortel

<lang wortel>!console.log @unlines ~!* 99..0 !? {

 0 "0 bottles of beer on the wall\n0 bottles of beer\nbetter go to the store and buy some more."
"{@x} bottle{@?@x{1 @e 's}} of beer on the wall\n{@x} bottle{@?@x{1 @e 's}} of beer\nTake one down, pass it around"


}</lang>

## Wrapl

<lang wrapl>MOD Bottles;

IMP IO.Terminal USE Out; IMP Std.String;

VAR i, s <- "s", ob <- "of beer", otw <- "on the wall",

   more <- "Take one down and pass it around", verse <- [];


EVERY i <- 99:to(0,-1) DO (

   (i = 1) & (s <- "");
(i = 0) & (s <- "s"; i <- "No more"; more <- "Go to the store and buy some more");
verse:put('. {i} bottle{s} {ob} {otw}.\n');
verse:put('\n{i} bottle{s} {ob} {otw}, {(i@String.T):lower} bottle{s} {ob}.\n{more}');


);

Out:write(verse[2,0]@(String.T, "") + verse[1]);

END Bottles.</lang>

## Wren

<lang wren>for (i in 99...0) {

 IO.print(i, " bottles of beer on the wall,")
IO.print(i, " bottles of beer,")
IO.print("Take one down, pass it around,")
IO.print(i - 1, " bottles of beer on the wall.\n")


}</lang>

## XPL0

<lang XPL0>code IntOut=11, Text=12; int B; [B:= 99; repeat IntOut(0, B); Text(0, " bottles of beer on the wall^M^J");

       IntOut(0, B);  Text(0, " bottles of beer^M^J");
Text(0, "Take one down, pass it around^M^J");
B:= B-1;
IntOut(0, B);  Text(0, " bottles of beer on the wall^M^J^J");


until B=0; ]</lang>

## Yorick

### Looped version

<lang yorick>bottles = 99; while(bottles) {

   write, format=" %d bottles of beer on the wall\n", bottles;
write, format=" %d bottles of beer\n", bottles;
write, "Take one down, pass it around";
write, format=" %d bottles of beer on the wall\n\n", --bottles;


}</lang>

### Vectorized version

<lang yorick>song = "%d bottles of beer on the wall\n"; song += "%d bottles of beer\n"; song += "Take one down, pass it around\n"; song += "%d bottles of beer on the wall\n"; beer = indgen(99:1:-1); write, format=song, beer, beer, beer-1;</lang>

## zkl

<lang zkl>[99..0,-1].pump(fcn(n){

  println(beers(n), " on the wall, ", beers(n).toLower(), ".\n",
n==0 and ("Go to the store and buy some more, 99 bottles of beer") or
("Take one down and pass it around, " + beers(n-1).toLower()),
" on the wall.\n")


}); fcn beers(n){

   (n==0 and "No more bottles" or (n==1 and "1 bottle" or "" + n + " bottles"))
+ " of beer"


}</lang>

Output:
99 bottles of beer on the wall, 99 bottles of beer.
Take one down and pass it around, 98 bottles of beer on the wall.
...
1 bottle of beer on the wall, 1 bottle of beer.
Take one down and pass it around, no more bottles of beer on the wall.

No more bottles of beer on the wall, no more bottles of beer.
Go to the store and buy some more, 99 bottles of beer on the wall.