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

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

Display the complete lyrics for the song:     99 Bottles of Beer on the Wall.

The beer song

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

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

... and so on, until reaching   0     (zero).

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

## 11l

Translation of: Python
L(i) (99..1).step(-1)   print(i‘ bottles of beer on the wall’)   print(i‘ bottles of beer’)   print(‘Take one down, pass it around’)   print((i - 1)" bottles of beer on the wall\n")

## 8th

 \ 99 bottles of beer on the wall:: allout "no more bottles" ;: just-one "1 bottle"  ;: yeah!	 dup . " bottles" ; [	' allout ,	' just-one ,	' yeah! ,] var, bottles : .bottles  dup 2 n:min bottles @ swap caseof ;: .beer     .bottles . " of beer" . ;: .wall     .beer " on the wall" . ;: .take     "  Take one down and pass it around" . ;: beers     .wall ", " . .beer '; putc cr			n:1- 0 max .take ", " . 			.wall '. putc cr drop ; ' beers 1 99 loop- bye

## AArch64 Assembly

Works with: as version Raspberry Pi 3B version Buster 64 bits
 /* ARM assembly AARCH64 Raspberry PI 3B *//*  program bootleBeer64.s   */  /*******************************************//* Constantes file                         *//*******************************************//* for this file see task include a file in language AArch64 assembly*/.include "../includeConstantesARM64.inc" .equ MAXI,   99 /*********************************//* Initialized data              *//*********************************/.dataszMessLine1:        .asciz "@ bottles of beer on the wall\n"szMessLine2:        .ascii "@ bottles of beer\n"                    .asciz "Take one down, pass it around\n"szMessLine3:        .asciz "@ bottles of beer on the wall\n\n" szMessLine4:       .ascii "\nNo more bottles of beer on the wall, no more bottles of beer.\n"                   .asciz "Go to the store and buy some more, 99 bottles of beer on the wall.\n" szCarriageReturn:   .asciz "\n"/*********************************//* UnInitialized data            *//*********************************/.bsssZoneConv:        .skip 24/*********************************//*  code section                 *//*********************************/.text.global main main:                            // entry of program     mov x2,#MAXI1:    mov x0,x2    ldr x1,qAdrsZoneConv    bl conversion10              // call decimal conversion    ldr x0,qAdrszMessLine1    ldr x1,qAdrsZoneConv         // insert conversion in message    bl strInsertAtCharInc    bl affichageMess     ldr x0,qAdrszMessLine2    ldr x1,qAdrsZoneConv         // insert conversion in message    bl strInsertAtCharInc    bl affichageMess     subs x0,x2,#1    ble 2f    ldr x1,qAdrsZoneConv    bl conversion10              // call decimal conversion    ldr x0,qAdrszMessLine3    ldr x1,qAdrsZoneConv         // insert conversion in message    bl strInsertAtCharInc    bl affichageMess2:    subs x2,x2,1    bgt 1b     ldr x0,qAdrszMessLine4    bl affichageMess 100:                                  // standard end of the program     mov x0, #0                        // return code    mov x8, #EXIT                     // request to exit program    svc #0                            // perform the system call qAdrszCarriageReturn:     .quad szCarriageReturnqAdrszMessLine1:          .quad szMessLine1qAdrszMessLine2:          .quad szMessLine2qAdrszMessLine3:          .quad szMessLine3qAdrszMessLine4:          .quad szMessLine4qAdrsZoneConv:            .quad sZoneConv /********************************************************//*        File Include fonctions                        *//********************************************************//* for this file see task include a file in language AArch64 assembly */.include "../includeARM64.inc"

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

or (With ABAP 7.40)

REPORT YCL_99_BOTTLES. DATA it_99_bottles TYPE TABLE OF string WITH EMPTY KEY.DATA(cr_lf) = cl_abap_char_utilities=>cr_lf.it_99_bottles = VALUE #(    FOR i = 99 THEN i - 1 UNTIL i = 0 ( COND string( LET  lv = ( i - 1 )                                                          lr = i && | bottles of beer on the wall|                                                                 && cr_lf                                                                 && i && | bottles of beer|                                                                 && cr_lf                                                                 && |Take one down, pass it around|                                                                 && cr_lf                                                                 && lv && | bottles of beer on the wall|                                                                 && cr_lf IN WHEN 1 = 1 THEN lr )                                      )                         ).cl_demo_output=>write( it_99_bottles ).cl_demo_output=>display( ).

## Action!

PROC Bottles(BYTE i)  IF i=0 THEN    Print("No more")  ELSE    PrintB(i)  FI  Print(" bottle")  IF i#1 THEN    Print("s")  FIRETURN PROC Main()  BYTE i=[99]   WHILE i>0  DO    Bottles(i) PrintE(" of beer on the wall,")    Bottles(i) PrintE(" of beer,")        Print("Take ")    IF i>1 THEN      Print("one")    ELSE      Print("it")    FI    PrintE(" down and pass it around,")    i==-1    Bottles(i) PrintE(" of beer on the wall.")    IF i>0 THEN      PutE()    FI  ODRETURN
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.

...

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 it down and pass it around,
No more bottles of beer on the wall.


## 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");		  }

### Simple version

with Ada.Text_Io; use Ada.Text_Io;  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;

### Concurrent version

with 1 task to print out the information and 99 tasks to specify the number of bottles

with Ada.Text_Io; use Ada.Text_Io; procedure Tasking_99_Bottles is   subtype Num_Bottles is Natural range 1..99;   task Print is      entry Set (Num_Bottles);   end Print;   task body Print is      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;   task type Counter(I : Num_Bottles);   task body Counter is   begin      Print.Set(I);   end Counter;   type Task_Access is access Counter;    Task_List : array(Num_Bottles) of Task_Access; begin   for I in Task_List'range loop -- Create 99 Counter tasks      Task_List(I) := new Counter(I);   end loop;end Tasking_99_Bottles;

## Aime

integer bottles; bottles = 99; do {    o_(bottles, " bottles of beer on the wall\n");    o_(bottles, " bottles of beer\n");    o_("Take one down, pass it around\n");    o_(bottles -= 1, " bottles of beer on the wall\n\n");} while (bottles);

## Algae

 # 99 Bottles of Beer on the Wall # in Algae # bottles.A for (i in 99:1:1) {    if (i != 1) {        printf("%d bottles of beer on the wall\n";i);        printf("%d bottles of beer...\n";i);        printf("you take on down and pass it around...\n");        if ( i == 2) {            printf("%d bottles of beer on the wall\n\n";i-1);        else            printf("%d bottles of beer on the wall\n\n";i-1);        }    else       printf("1 bottle of beer on the wall\n");       printf("1 bottle of beer...\n");       printf("you take on down and pass it around..\n");       printf("no more bottles of beer on the wall!\n\n");    }}

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

## ALGOL-M

 BEGIN COMMENT PRINT LYRICS TO "99 BOTTLES OF BEER ON THE WALL"; STRING FUNCTION BOTTLE(N); % GIVE CORRECT GRAMMATICAL FORM %INTEGER N;BEGIN   IF N = 1 THEN      BOTTLE := " BOTTLE"   ELSE      BOTTLE := " BOTTLES";END; INTEGER N; N := 99;WHILE N > 0 DO   BEGIN      WRITE(N, BOTTLE(N), " OF BEER ON THE WALL,");      WRITEON(N, BOTTLE(N), " OF BEER");      WRITE("TAKE ONE DOWN AND PASS IT AROUND, ");      N := N - 1;      IF N = 0 THEN          WRITEON("NO MORE")      ELSE          WRITEON(N);      WRITEON(BOTTLE(N), " OF BEER ON THE WALL");      WRITE(" "); % BLANK LINE BETWEEN STANZAS %   END;WRITE("THANKS FOR SINGING ALONG!"); END

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

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

<?xml version="1.0"?><project name="n bottles" default="99_bottles">   <!-- ant-contrib.sourceforge.net for arithmetic and if -->  <taskdef resource="net/sf/antcontrib/antcontrib.properties"/>   <!-- start count of bottles, you can set this with    e.g. ant -f 99.xml -Dcount=10 -->  <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"/> <math result="result" operand1="${number}" operation="-" operand2="1" datatype="int"/>     <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>

## Apex

    for(Integer i = 99; i=0; i--){      system.debug(i + ' bottles of beer on the wall');      system.debug('\n');      system.debug(i + ' bottles of beer on the wall');      system.debug(i + ' bottles of beer');      system.debug('take one down, pass it around');   } 

## APL

Works with: Dyalog APL
Works with: GNU APL

### Classic version

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}

     ⍝ Dyalog APL invocation
99↑beer¨ ⌽(1-⎕IO)+⍳99

     ⍝ GNU APL invocation (↑ and ⊃ differ, traditional APL2 meanings)
⊃beer¨ ⌽(1-⎕IO)+⍳99


### One line version

     ⍝ Dyalog and GNU APL
⍪{(⍕⍵),' bottles of beer on the wall, take one down and pass it around, ',(⍕⍵-1),' bottles of beer on the wall'}¨⌽⍳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

### Iteration

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"endlog "No more bottles of beer on the wall!"

### Declaration

-- BRIEF -----------------------------------------------------------------------on run    set localisations to ¬        {"on the wall", ¬            "Take one down, pass it around", ¬            "Better go to the store to buy some more", "bottle"}     intercalate("\n\n", ¬        (map(curry(incantation)'s |λ|(localisations), enumFromTo(99, 0))))end run  -- DECLARATIVE ----------------------------------------------------------------- -- incantation :: [String] -> Int -> Stringon incantation(xs, n)    script asset        on |λ|(n)            unwords({(n as string), item -1 of xs & cond(n ≠ 1, "s", "")})        end |λ|    end script     script store        on |λ|(n)            unwords({asset's |λ|(n), item 1 of xs})        end |λ|    end script     set {distribute, solve} to items 2 thru 3 of xs    if n > 0 then        unlines({store's |λ|(n), asset's |λ|(n), distribute, store's |λ|(n - 1)})    else        solve    end ifend incantation  -- GENERICALLY DYSFUNCTIONAL --------------------------------------------------- -- cond :: Bool -> a -> a -> aon cond(bln, f, g)    if bln then        f    else        g    end ifend cond -- curry :: (Script|Handler) -> Scripton curry(f)    script        on |λ|(a)            script                on |λ|(b)                    |λ|(a, b) of mReturn(f)                end |λ|            end script        end |λ|    end scriptend curry -- enumFromTo :: Int -> Int -> [Int]on enumFromTo(m, n)    if m > n then        set d to -1    else        set d to 1    end if    set lst to {}    repeat with i from m to n by d        set end of lst to i    end repeat    return lstend enumFromTo -- intercalate :: Text -> [Text] -> Texton intercalate(strText, lstText)    set {dlm, my text item delimiters} to {my text item delimiters, strText}    set strJoined to lstText as text    set my text item delimiters to dlm    return strJoinedend intercalate -- map :: (a -> b) -> [a] -> [b]on map(f, xs)    tell mReturn(f)        set lng to length of xs        set lst to {}        repeat with i from 1 to lng            set end of lst to |λ|(item i of xs, i, xs)        end repeat        return lst    end tellend map -- Lift 2nd class handler function into 1st class script wrapper -- mReturn :: Handler -> Scripton mReturn(f)    if class of f is script then        f    else        script            property |λ| : f        end script    end ifend mReturn -- unlines :: [String] -> Stringon unlines(xs)    intercalate(linefeed, xs)end unlines -- unwords :: [String] -> Stringon unwords(xs)    intercalate(space, xs)end unwords

## ATS

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

## AWK

### Regular version

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

# 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!"}
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!


## Axe

Pauses are added to accommodate the small calculator screen so all of the text can be read.

99→BWhile B Disp B▶Dec," BOTTLES OF","BEER ON THE WALL" Disp B▶Dec," BOTTLES OF","BEER",i,i getKeyʳ Disp "TAKE ONE DOWN",i,"PASS IT AROUND",i B-- Disp B▶Dec," BOTTLES OF","BEER ON THE WALL",i getKeyʳEnd

## Babel

-- beer.sp {b  " bottles of beer"         < bi { itoa << }                < bb { bi ! b << w << "\n" << } < w  " on the wall"             < beer    {<-        { iter 1 + dup           <- bb ! ->           bi ! b << "\n" <<          "Take one down, pass it around\n" <<          iter bb ! "\n" << }    ->     times}    < } -- At the prompt, type 'N beer !' (no quotes), where N is the number of stanzas you desire

## Battlestar

 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" // Reserve 1024 bytes in the .bss sectionvar x 1024 // Write two digits, based on the value in afun printnum    b = a    a >= 10        a /= 10        // modulo is in the d register after idiv        b = d        a += 48 // ASCII value for '0'        print(chr(a))    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, "        x = bottle        x += plural        x += ofbeer        x += wall        x += sep        print(x)         // Retrieve and print the number        stack -> a        printnum()         // N, "bottles of beer.\nTake one down and pass it around,"        x = bottle        x += plural        x += ofbeer        x += dotnl        x += takedown        print(x)         // 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 + a blank line        x = ofbeer        x += wall        x += dotnl        x += nl        print(x)         // 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()        x = bottle        x += ofbeer        x += wall        x += sep        print(x)         // "1"        a = 1        printnum()         // "bottle of beer. Take one down and pass it around,"        // "no more bottles of beer on the wall."        // Blank line        // "No more bottles of beer on the wall,"        // "no more bottles of beer."        // "Go to the store and buy some more,"        x = bottle        x += ofbeer        x += dotnl        x += takedown        x += l_no        x += more        x += wall        x += dotnl        x += nl        x += u_no        x += more        x += wall        x += sep        x += l_no        x += more        x += dotnl        x += store        print(x)         // "99"        a = 99        printnum()         // "bottles of beer on the wall."        x = bottle        x += plural        x += ofbeer        x += wall        x += dotnl        print(x)    endend // vim: set syntax=c ts=4 sw=4 et: 

## Bc

Works with: GNU bc version 1.06
i = 99;while ( 1 ) {     print i , " bottles of beer on the wall\n";     print i , " bottles of beer\nTake one down, pass it around\n";     if (i == 2) {          break     }     print --i , " bottles of beer on the wall\n";} print --i , " bottle of beer on the wall\n";print   i , " bottle of beer on the wall\n";print   i , " bottle of beer\nTake it down, pass it around\nno more bottles of beer on the wall\n";quit

## BCPL

get "libhdr" let number(n) be    test n=0        then writes("No more")        else writen(n) let plural(n) be    test n=1        then writes(" bottle")        else writes(" bottles") let bottles(n) be$( number(n) plural(n)$) let verse(n) be$( bottles(n) writes(" of beer on the wall,*N") bottles(n) writes(" of beer,*NTake ") test n=1 then writes("it") else writes("one") writes(" down and pass it around,*N") bottles(n-1) writes(" of beer on the wall!*N*N")$) let start() be    for n = 99 to 1 by -1 do verse(n)

## beeswax

Straightforward implementation, displaying the full lyrics given on [ http://99-bottles-of-beer.net/ ]

   >       NN      p> d#_8~2~(P~3~.~1~>{ bottles of beer on the wall, { bottles of beer.qd.llaw eht no reeb fo selttob {pLM ,dnuora ti ssap dna nwod eno ekaTN<q.llaw eht no reeb fo elttob  {< >        NN       >{ bottle of beer on the wall, { bottle of beer.N  qpN .llaw eht no reeb fo selttob erom on ,dnuora ti ssap dna nwod eno ekaT<>NNo more bottles of beer on the wall, no more bottles of beer.N  q;.llaw eht no reeb fo selttob 99 ,erom emos yub dna erots eht ot oG< 

A much more “economic” version that tries to avoid repetition at the price of complicated conditional jumps and self-modifying code that takes up more place than the actual strings themselves. Output is the same as in the straightforward version.

 #[email protected][email protected]~P9zE       Np[email protected]@.~2~.++~5zE      n>op>0f1ff#             q   erom <           #h3~1z<           #h3~1z<    #h3~1z<d_8~2~(P~3~.  ~1~>"b{>X^^^ bottle  of beer@g"pX on the wallg"pX   ,  @p #               > d   <#XL#^^^^^s#            #  ##      #        >    .[email protected]  X#                   b                                             <            <  <                         >~L#^^^^s#      #h3~1zX    #h3~1z<#      #  #      # #               d             #h3~1z<#            #> .   g"pXN @"p Take one down and p>^^^^^^^^^;     .#   b              XgNN                    <       bM ,dnuora ti ssap<d^^^^^^^^^^^^^^^^X~3~P(~2~8 ,erom emos yub dna erots eht ot oG< 

## BlooP

Output is always in caps in the interpreter I use, but I typed the input in correct case to spare those whose interpreter might do lowercase and don't want to have this song shouted at them ;D.

 DEFINE PROCEDURE ''MINUS'' [A,B]:BLOCK 0: BEGIN  IF A < B, THEN:    QUIT BLOCK 0;  LOOP AT MOST A TIMES:  BLOCK 1: BEGIN    IF OUTPUT + B = A, THEN:      QUIT BLOCK 0;    OUTPUT <= OUTPUT + 1;  BLOCK 1: END;BLOCK 0: END. DEFINE PROCEDURE ''BOTTLES'' [COUNT]:BLOCK 0: BEGIN	CELL(0) <= COUNT;	LOOP COUNT + 1 TIMES: 	BLOCK 1: BEGIN 		IF CELL(0) > 1, THEN:			PRINT[CELL(0), ' bottles of beer on the wall, ', CELL(0), ' bottles of beer. Take one down, pass it around, ', MINUS[CELL(0), 1], ' bottles of beer on the wall.']; 		IF CELL(0) = 1, THEN:      PRINT['1 botle of beer on the wall, 1 bottle of beer. Take one down, pass it around, No more bottles of beer on the wall.'];     IF CELL(0) = 0, THEN:      PRINT['No more bottles of beer on the wall, no more bottles of beer. Go to the store, buy 99 more, 99 bottles of beer on the wall!'];     CELL(0) <= MINUS[CELL(0), 1]; 	BLOCK 1: END;BLOCK 0: END. BOTTLES[99]; 

## 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: {BottlesOfBeer.bra See http://99-bottles-of-beer.net/} X= new= n upper nbottles lyrics . 99:?n & ( upper = [email protected](!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 See http://99-bottles-of-beer.net/} " , "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;  ## Brainf*** ## 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." ## BQN Pl ← {(𝕩≠1)/"s"}{𝕨∾(@+10)∾𝕩}´{(•Fmt 𝕨)∾" "∾𝕩}´¨∾{ ⟨ ⟨𝕩,"bottle"∾(Pl 𝕩)∾" of beer on the wall"⟩ ⟨𝕩,"bottle"∾(Pl 𝕩)∾" of beer"⟩ ⟨"Take one down, pass it around"⟩ ⟨𝕩-1,"bottle"∾(Pl 𝕩-1)∾" of beer on the wall"∾@+10⟩ ⟩}¨⌽1+↕99 •Fmt is used to convert numbers to strings. Pl tells whether the number is singular or plural. Then, the two folds join all the individual lines together. ## C Translation of: C++ ### The simple solution /* * 99 Bottles, C, KISS (i.e. keep it simple and straightforward) version */ #include <stdio.h> int main(void){ int n; for( n = 99; n > 2; n-- ) printf( "%d bottles of beer on the wall, %d bottles of beer.\n" "Take one down and pass it around, %d bottles of beer on the wall.\n\n", n, n, n - 1); printf( "2 bottles of beer on the wall, 2 bottles of beer.\n" "Take one down and pass it around, 1 bottle of beer on the wall.\n\n" "1 bottle of beer on the wall, 1 bottle of beer.\n" "Take one down and pass it around, no more bottles of beer on the wall.\n\n" "No more bottles of beer on the wall, no more bottles of beer.\n" "Go to the store and buy some more, 99 bottles of beer on the wall.\n"); return 0;} ### A recursive solution #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;} ### Code golf #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");} ### 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: #include <stdlib.h>#include <stdio.h> #define BOTTLE(nstr) nstr " bottles of beer" #define WALL(nstr) BOTTLE(nstr) " on the wall" #define PART1(nstr) WALL(nstr) "\n" BOTTLE(nstr) \ "\nTake one down, pass it around\n" #define PART2(nstr) WALL(nstr) "\n\n" #define MIDDLE(nstr) PART2(nstr) PART1(nstr) #define SONG PART1("100") CD2 PART2("0") #define CD2 CD3("9") CD3("8") CD3("7") CD3("6") CD3("5") \ CD3("4") CD3("3") CD3("2") CD3("1") CD4("") #define CD3(pre) CD4(pre) MIDDLE(pre "0") #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;} 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):  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);} ## C# 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(); } } }} ### C#6 Implementation Works with: C# version 6+ using System;class Program{ static void Main() { Func<int, bool, string> f = (x, y) =>$"{(x == 0 ? "No more" : x.ToString())} bottle{(x == 1 ? "" : "s")} of beer{(y ? " on the wall" : "")}\r\n";        for (int i = 99; i > 0; i--)            Console.WriteLine($"{f(i, true)}{f(i, false)}Take one down, pass it around\r\n{f(i - 1, true)}"); }} ### Linq Implementation Works with: C# version 6+ using System;using System.Linq; class Program{ static void Main() { Enumerable.Range(1, 99).Reverse().Select(x =>$"{x} bottle{(x == 1 ? "" : "s")} of beer on the wall, {x} bottle{(x == 1 ? "" : "s")} of beer!\n" +            $"Take {(x == 1 ? "it" : "one")} down, pass it around, {(x == 1 ? "no more" : (x - 1).ToString())} bottles of beer on the wall!\n" ).ToList().ForEach(x => Console.WriteLine(x)); }} ### Flexible Version using System;using System.Globalization;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); } }} ### Using Formatting Works with: C# version 3+ class songs{ static void Main(string[] args) { beer(3); } 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...."); } }} 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 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+ 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)); }} ### A Fun One 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();} ### Using recursion 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); }} ### Using a While Loop static void Main(string[] args){ int numBottles = 99; while (numBottles > 0) { if (numBottles > 1) { WriteLine("{0} bottles of beer on the wall, {0} bottles of beer.", numBottles); numBottles -= 1; WriteLine("Take one down, pass it around, {0} bottles of beer on the wall.\n", numBottles); } else { WriteLine("{0} bottle of beer on the wall, {0} bottle of beer.", numBottles); numBottles -= 1; WriteLine("Take one down, pass it around, no more bottles of beer on the wall.\n"); } } WriteLine("No more bottles of beer on the wall, no more bottles of beer."); WriteLine("Go to the store to buy some more, 99 bottles of beer on the wall...");} ## C++ ### The simple solution Works with: g++ version 4.8.1 #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"; }} ### 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: #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;} ### A function template solution Function templates are a different approach to template metaprogramming: #include <iostream> template<unsigned int N> void bottles(){ std::cout << N << " bottles of beer on the wall\n" << N << " bottles of beer\n" << "Take one down, pass it around\n" << N - 1 << " bottles of beer on the wall\n\n"; bottles<N-1>();} template<> void bottles<0>(){ std::cout<<"No more bottles of beer on the wall\n" "No more bottles of beer\n" "Go to the store and buy some more\n" "99 bottles of beer on the wall...\n\n";} int main(){ bottles<99>();}  ### A Recursive solution #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;}  ### 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: #include <iostream>#include <ostream> #define BOTTLE(nstr) nstr " bottles of beer" #define WALL(nstr) BOTTLE(nstr) " on the wall" #define PART1(nstr) WALL(nstr) "\n" BOTTLE(nstr) \ "\nTake one down, pass it around\n" #define PART2(nstr) WALL(nstr) "\n\n" #define MIDDLE(nstr) PART2(nstr) PART1(nstr) #define SONG PART1("100") CD2 PART2("0") #define CD2 CD3("9") CD3("8") CD3("7") CD3("6") CD3("5") \ CD3("4") CD3("3") CD3("2") CD3("1") CD4("") #define CD3(pre) CD4(pre) MIDDLE(pre "0") #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;} ### Bottled Version  //>,_ //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!!! ## Ceylon shared void ninetyNineBottles() { String bottles(Integer count) => "count == 0 then "No" else count bottlecount == 1 then "" else "s"".normalized; for(i in 99..1) { print("bottles(i) of beer on the wall bottles(i) of beer! Take one down, pass it around bottles(i - 1) of beer on the wall!\n"); }} ## 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  /*********************************************************************** * 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: [email protected] * * * 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 lyricsvar LyricsSpace: domain(1) = {1..numVerses}; // array of lyricsvar 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, ";}  ## Chef ## Cind  execute() { // this class provides synchronization // to get unique number of the bottle class monitor giver { int number = 100; .get() { return --number; } } var g = new giver(); // start 99 concurrently worked threads // each thread gets own number of the bottle and prints out his own verse // (notice that the output lines from the threads will be mixed together) {#[99] int nr = g.get(); // get own number host.println(nr," bottles of beer on the wall, "+nr+" bottles of beer"); host.print("Take one down, pass it around,"); if (nr > 1) { host.println((nr-1)," bottles of beer on the wall."); } else { host.println("no more bottles of beer on the wall."); } } host.println("No more bottles of beer on the wall, no more bottles of beer."); host.println("Go to the store and buy some more, 99 bottles of beer on the wall."); return 0;}  ## 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)))));}  ## Clio fn bottle n: n -> if = 0: 'no more bottles' elif = 1: n + ' bottle' else: n + ' bottles' [99:0] -> * (@eager) fn i: i -> bottle -> print (transform i: sentence-case) 'of beer on the wall,' @ 'of beer.' if i = 0: 'Go to the store, buy some more, 99 bottles of beer on the wall.' -> print else: i - 1 -> bottle -> print 'Take one down and pass it around,' @ 'of beer on the wall.\n' ## 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))))) ## Clojure (defn paragraph [num] (str num " bottles of beer on the wall\n" num " bottles of beer\n" "Take one down, pass it around\n" (dec num) " bottles of beer on the wall.\n")) (defn lyrics [] (let [numbers (range 99 0 -1) paragraphs (map paragraph numbers)] (clojure.string/join "\n" paragraphs))) (print (lyrics)) Or, using cl-format: Translation of: Common Lisp (clojure.pprint/cl-format true "~{~[~^~]~:*~D bottle~:P of beer on the wall~%~:*~D bottle~:P of beerTake one down, pass it around,~%~D bottle~:P~:* of beer on the wall.~2%~}" (range 99 0 -1)) ## CLU bottles = proc (n: int) returns (string) if n<0 then return("99 bottles") elseif n=0 then return("No more bottles") elseif n=1 then return("1 bottle") else return(int$unparse(n) || " bottles")    endend bottles thirdline = proc (n: int) returns (string)    if n=0 then        return("Go to the store and buy some more,\n")    else        s: string        if n=1 then s := "it"        else s := "one"        end        return("Take " || s || " down and pass it around,\n");    endend thirdline verse = proc (n: int) returns (string)    v: string := bottles(n) || " bottles of beer on the wall,\n"    v := v || bottles(n) || " bottles of beer,\n"    v := v || thirdline(n)    v := v || bottles(n-1) || " bottles of beer on the wall.\n\n"    return(v)end verse start_up = proc ()    po: stream := stream$primary_output() for n: int in int$from_to_by(99, 0, -1) do        stream$puts(po, verse(n)) endend start_up ## COBOL Works with: OpenCOBOL version 1.1 Free form version. 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. Another free-form version, without using DISPLAY NO ADVANCING. 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. A more concise version that adheres to the minimum guidelines. Leading zeros are not suppressed. (OpenCOBOL - 1.1.0) 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. ## 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]  With completely different approach... 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' 

or as a one liner...

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]

or another completely different one liner

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

## ColdFusion

### Classic tag based CFML

<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<br>    #x# bottle#plur# of beer<br>    Take one down, pass it around<br>    #iif(x is 1,DE("No more"),"x-1")# bottle#iif(x is 2,"",DE("s"))# of beer on the wall<br><br>  </cfloop></cfoutput>

or if you prefer: (identical output, grammatically correct to the last stanza)

### CFScript

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

## Comefrom0x10

bottles = ' bottles 'remaining = 99one_less_bottle = remainingdepluralize  comefrom drinking if one_less_bottle is 1  bottles = ' bottle ' drinking  comefrom if remaining is one_less_bottle  remaining bottles 'of beer on the wall'  remaining bottles 'of beer'  'Take one down, pass it around'  one_less_bottle = remaining - 1  one_less_bottle bottles 'of beer on the walln'  remaining = remaining - 1   comefrom if one_less_bottle is 0  'No more bottles of beer on the wall'
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
No more bottles of beer on the wall


## Cowgol

include "cowgol.coh"; sub Bottles(n: uint8) is    if n == 0 then        print("No more");    else        print_i8(n);    end if;     print(" bottle");    if n != 1 then        print("s");    end if;end sub; sub Verse(n: uint8) is    Bottles(n);    print(" of beer on the wall,\n");    Bottles(n);    print(" of beer,\n");    print("Take ");    if n == 1 then        print("it");    else        print("one");    end if;    print(" down and pass it around,\n");    Bottles(n-1);    print(" of beer on the wall.\n\n");end sub; var verse: uint8 := 99;while verse > 0 loop    Verse(verse);    verse := verse - 1;end loop;
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.

97 bottles of beer on the wall,
97 bottles of beer,
Take one down and pass it around,
96 bottles of beer on the wall.

96 bottles of beer on the wall,
96 bottles of beer,
Take one down and pass it around,
95 bottles of beer on the wall.

95 bottles of beer on the wall,
95 bottles of beer,
Take one down and pass it around,
94 bottles of beer on the wall.

94 bottles of beer on the wall,
94 bottles of beer,
Take one down and pass it around,
93 bottles of beer on the wall.

93 bottles of beer on the wall,
93 bottles of beer,
Take one down and pass it around,
92 bottles of beer on the wall.

92 bottles of beer on the wall,
92 bottles of beer,
Take one down and pass it around,
91 bottles of beer on the wall.

91 bottles of beer on the wall,
91 bottles of beer,
Take one down and pass it around,
90 bottles of beer on the wall.

90 bottles of beer on the wall,
90 bottles of beer,
Take one down and pass it around,
89 bottles of beer on the wall.

89 bottles of beer on the wall,
89 bottles of beer,
Take one down and pass it around,
88 bottles of beer on the wall.

88 bottles of beer on the wall,
88 bottles of beer,
Take one down and pass it around,
87 bottles of beer on the wall.

87 bottles of beer on the wall,
87 bottles of beer,
Take one down and pass it around,
86 bottles of beer on the wall.

86 bottles of beer on the wall,
86 bottles of beer,
Take one down and pass it around,
85 bottles of beer on the wall.

85 bottles of beer on the wall,
85 bottles of beer,
Take one down and pass it around,
84 bottles of beer on the wall.

84 bottles of beer on the wall,
84 bottles of beer,
Take one down and pass it around,
83 bottles of beer on the wall.

83 bottles of beer on the wall,
83 bottles of beer,
Take one down and pass it around,
82 bottles of beer on the wall.

82 bottles of beer on the wall,
82 bottles of beer,
Take one down and pass it around,
81 bottles of beer on the wall.

81 bottles of beer on the wall,
81 bottles of beer,
Take one down and pass it around,
80 bottles of beer on the wall.

80 bottles of beer on the wall,
80 bottles of beer,
Take one down and pass it around,
79 bottles of beer on the wall.

79 bottles of beer on the wall,
79 bottles of beer,
Take one down and pass it around,
78 bottles of beer on the wall.

78 bottles of beer on the wall,
78 bottles of beer,
Take one down and pass it around,
77 bottles of beer on the wall.

77 bottles of beer on the wall,
77 bottles of beer,
Take one down and pass it around,
76 bottles of beer on the wall.

76 bottles of beer on the wall,
76 bottles of beer,
Take one down and pass it around,
75 bottles of beer on the wall.

75 bottles of beer on the wall,
75 bottles of beer,
Take one down and pass it around,
74 bottles of beer on the wall.

74 bottles of beer on the wall,
74 bottles of beer,
Take one down and pass it around,
73 bottles of beer on the wall.

73 bottles of beer on the wall,
73 bottles of beer,
Take one down and pass it around,
72 bottles of beer on the wall.

72 bottles of beer on the wall,
72 bottles of beer,
Take one down and pass it around,
71 bottles of beer on the wall.

71 bottles of beer on the wall,
71 bottles of beer,
Take one down and pass it around,
70 bottles of beer on the wall.

70 bottles of beer on the wall,
70 bottles of beer,
Take one down and pass it around,
69 bottles of beer on the wall.

69 bottles of beer on the wall,
69 bottles of beer,
Take one down and pass it around,
68 bottles of beer on the wall.

68 bottles of beer on the wall,
68 bottles of beer,
Take one down and pass it around,
67 bottles of beer on the wall.

67 bottles of beer on the wall,
67 bottles of beer,
Take one down and pass it around,
66 bottles of beer on the wall.

66 bottles of beer on the wall,
66 bottles of beer,
Take one down and pass it around,
65 bottles of beer on the wall.

65 bottles of beer on the wall,
65 bottles of beer,
Take one down and pass it around,
64 bottles of beer on the wall.

64 bottles of beer on the wall,
64 bottles of beer,
Take one down and pass it around,
63 bottles of beer on the wall.

63 bottles of beer on the wall,
63 bottles of beer,
Take one down and pass it around,
62 bottles of beer on the wall.

62 bottles of beer on the wall,
62 bottles of beer,
Take one down and pass it around,
61 bottles of beer on the wall.

61 bottles of beer on the wall,
61 bottles of beer,
Take one down and pass it around,
60 bottles of beer on the wall.

60 bottles of beer on the wall,
60 bottles of beer,
Take one down and pass it around,
59 bottles of beer on the wall.

59 bottles of beer on the wall,
59 bottles of beer,
Take one down and pass it around,
58 bottles of beer on the wall.

58 bottles of beer on the wall,
58 bottles of beer,
Take one down and pass it around,
57 bottles of beer on the wall.

57 bottles of beer on the wall,
57 bottles of beer,
Take one down and pass it around,
56 bottles of beer on the wall.

56 bottles of beer on the wall,
56 bottles of beer,
Take one down and pass it around,
55 bottles of beer on the wall.

55 bottles of beer on the wall,
55 bottles of beer,
Take one down and pass it around,
54 bottles of beer on the wall.

54 bottles of beer on the wall,
54 bottles of beer,
Take one down and pass it around,
53 bottles of beer on the wall.

53 bottles of beer on the wall,
53 bottles of beer,
Take one down and pass it around,
52 bottles of beer on the wall.

52 bottles of beer on the wall,
52 bottles of beer,
Take one down and pass it around,
51 bottles of beer on the wall.

51 bottles of beer on the wall,
51 bottles of beer,
Take one down and pass it around,
50 bottles of beer on the wall.

50 bottles of beer on the wall,
50 bottles of beer,
Take one down and pass it around,
49 bottles of beer on the wall.

49 bottles of beer on the wall,
49 bottles of beer,
Take one down and pass it around,
48 bottles of beer on the wall.

48 bottles of beer on the wall,
48 bottles of beer,
Take one down and pass it around,
47 bottles of beer on the wall.

47 bottles of beer on the wall,
47 bottles of beer,
Take one down and pass it around,
46 bottles of beer on the wall.

46 bottles of beer on the wall,
46 bottles of beer,
Take one down and pass it around,
45 bottles of beer on the wall.

45 bottles of beer on the wall,
45 bottles of beer,
Take one down and pass it around,
44 bottles of beer on the wall.

44 bottles of beer on the wall,
44 bottles of beer,
Take one down and pass it around,
43 bottles of beer on the wall.

43 bottles of beer on the wall,
43 bottles of beer,
Take one down and pass it around,
42 bottles of beer on the wall.

42 bottles of beer on the wall,
42 bottles of beer,
Take one down and pass it around,
41 bottles of beer on the wall.

41 bottles of beer on the wall,
41 bottles of beer,
Take one down and pass it around,
40 bottles of beer on the wall.

40 bottles of beer on the wall,
40 bottles of beer,
Take one down and pass it around,
39 bottles of beer on the wall.

39 bottles of beer on the wall,
39 bottles of beer,
Take one down and pass it around,
38 bottles of beer on the wall.

38 bottles of beer on the wall,
38 bottles of beer,
Take one down and pass it around,
37 bottles of beer on the wall.

37 bottles of beer on the wall,
37 bottles of beer,
Take one down and pass it around,
36 bottles of beer on the wall.

36 bottles of beer on the wall,
36 bottles of beer,
Take one down and pass it around,
35 bottles of beer on the wall.

35 bottles of beer on the wall,
35 bottles of beer,
Take one down and pass it around,
34 bottles of beer on the wall.

34 bottles of beer on the wall,
34 bottles of beer,
Take one down and pass it around,
33 bottles of beer on the wall.

33 bottles of beer on the wall,
33 bottles of beer,
Take one down and pass it around,
32 bottles of beer on the wall.

32 bottles of beer on the wall,
32 bottles of beer,
Take one down and pass it around,
31 bottles of beer on the wall.

31 bottles of beer on the wall,
31 bottles of beer,
Take one down and pass it around,
30 bottles of beer on the wall.

30 bottles of beer on the wall,
30 bottles of beer,
Take one down and pass it around,
29 bottles of beer on the wall.

29 bottles of beer on the wall,
29 bottles of beer,
Take one down and pass it around,
28 bottles of beer on the wall.

28 bottles of beer on the wall,
28 bottles of beer,
Take one down and pass it around,
27 bottles of beer on the wall.

27 bottles of beer on the wall,
27 bottles of beer,
Take one down and pass it around,
26 bottles of beer on the wall.

26 bottles of beer on the wall,
26 bottles of beer,
Take one down and pass it around,
25 bottles of beer on the wall.

25 bottles of beer on the wall,
25 bottles of beer,
Take one down and pass it around,
24 bottles of beer on the wall.

24 bottles of beer on the wall,
24 bottles of beer,
Take one down and pass it around,
23 bottles of beer on the wall.

23 bottles of beer on the wall,
23 bottles of beer,
Take one down and pass it around,
22 bottles of beer on the wall.

22 bottles of beer on the wall,
22 bottles of beer,
Take one down and pass it around,
21 bottles of beer on the wall.

21 bottles of beer on the wall,
21 bottles of beer,
Take one down and pass it around,
20 bottles of beer on the wall.

20 bottles of beer on the wall,
20 bottles of beer,
Take one down and pass it around,
19 bottles of beer on the wall.

19 bottles of beer on the wall,
19 bottles of beer,
Take one down and pass it around,
18 bottles of beer on the wall.

18 bottles of beer on the wall,
18 bottles of beer,
Take one down and pass it around,
17 bottles of beer on the wall.

17 bottles of beer on the wall,
17 bottles of beer,
Take one down and pass it around,
16 bottles of beer on the wall.

16 bottles of beer on the wall,
16 bottles of beer,
Take one down and pass it around,
15 bottles of beer on the wall.

15 bottles of beer on the wall,
15 bottles of beer,
Take one down and pass it around,
14 bottles of beer on the wall.

14 bottles of beer on the wall,
14 bottles of beer,
Take one down and pass it around,
13 bottles of beer on the wall.

13 bottles of beer on the wall,
13 bottles of beer,
Take one down and pass it around,
12 bottles of beer on the wall.

12 bottles of beer on the wall,
12 bottles of beer,
Take one down and pass it around,
11 bottles of beer on the wall.

11 bottles of beer on the wall,
11 bottles of beer,
Take one down and pass it around,
10 bottles of beer on the wall.

10 bottles of beer on the wall,
10 bottles of beer,
Take one down and pass it around,
9 bottles of beer on the wall.

9 bottles of beer on the wall,
9 bottles of beer,
Take one down and pass it around,
8 bottles of beer on the wall.

8 bottles of beer on the wall,
8 bottles of beer,
Take one down and pass it around,
7 bottles of beer on the wall.

7 bottles of beer on the wall,
7 bottles of beer,
Take one down and pass it around,
6 bottles of beer on the wall.

6 bottles of beer on the wall,
6 bottles of beer,
Take one down and pass it around,
5 bottles of beer on the wall.

5 bottles of beer on the wall,
5 bottles of beer,
Take one down and pass it around,
4 bottles of beer on the wall.

4 bottles of beer on the wall,
4 bottles of beer,
Take one down and pass it around,
3 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 it down and pass it around,
No more bottles of beer on the wall.

## Crystal

99.downto(1) do |n|                                                               puts "#{n} bottle#{n > 1 ? "s" : ""} of beer on the wall"                       puts "#{n} bottle#{n > 1 ? "s" : ""} of beer"                                   puts "Take one down, pass it around"                                            puts "#{n-1} bottle#{n > 2 ? "s" : ""} of beer on the wall\n\n" if n > 1      end                                                                             puts "No more bottles of beer on the wall"

## D

### Simple Solution

Works with: D version 2

Based on Steward Gordon's code at: 99-bottles-of-beer.net.

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."); }

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

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

### Template Meta-Programming Solution

Uses D template meta-programming and recursion to pre-generate the song lyrics and prints it at compile via pragma(msg,...)

 module bottles; template BeerSong(int Bottles){	static if (Bottles == 1)	{		enum BeerSong = "1 bottle of beer on the wall\n" ~ 		"1 bottle of beer\ntake it down, pass it around\n" ~ "		no more bottles of beer on the wall\n";	}	else	{		enum BeerSong = Bottles.stringof ~ " bottles of beer on the wall\n" ~ 		Bottles.stringof ~ " bottles of beer\ntake it down, pass it around\n" ~ 		BeerSong!(Bottles-1);	}} pragma(msg,BeerSong!99); void main(){}

## Dart

// Making use of polymorphism

main() {  BeerSong beerSong = BeerSong();  //pass a 'starting point' and 'end point' as parameters respectively  String printTheLyrics = beerSong.recite(99, 1).join('\n');  print(printTheLyrics);  } class Song {  String bottleOnTheWall(int index) {    String bottleOnTheWallText =        '$index bottles of beer on the wall,$index bottles of beer,';    return bottleOnTheWallText;  }   String bottleTakenDown(int index) {    String englishGrammar = (index >= 2) ? 'bottle' : 'bottles';    String bottleTakenDownText =        'Take one down and pass it around, ${index - 1}$englishGrammar of beer on the wall.';    return bottleTakenDownText;  }} class BeerSong extends Song {  @override  String bottleOnTheWall(int index) {    String originalText = super.bottleOnTheWall(index);    if (index < 2) {      String bottleOnTheWallText =          '$index bottle of beer on the wall,$index bottle of beer,';      return bottleOnTheWallText;    }    return originalText;  }   @override  String bottleTakenDown(int index) {    if (index < 2) {      String bottleTakenDownText =          'Take it down and pass it around, no more bottles of beer on the wall.';      return bottleTakenDownText;    }    String originalText = super.bottleTakenDown(index);    return originalText;  }   List<String> recite(int actualBottleOnTheWall, int remainingBottleOnTheWall) {    List<String> theLyrics = [];    for (int index = actualBottleOnTheWall;        index >= remainingBottleOnTheWall;        index--) {      String onTheWall = bottleOnTheWall(index);      String takenDown = bottleTakenDown(index);      theLyrics.add(onTheWall);      theLyrics.add(takenDown);      theLyrics.add('');    }    return theLyrics;  }} }

## Dc

Works with: GNU dc
Works with: OpenBSD dc
[  dnrpr  dnlBP  lCP  1-dnrp  rd2r >L]sL [Take one down, pass it around]sC[ bottles of beer]sB[ bottles of beer on the wall]99 lLx dnrpsAdnlBPlCP1-dn[ bottle of beer on the wall]prdnrpsAn[ bottle of beer]P[Take it down, pass it around]P[no more bottles of beer on the wall]P

Similar to the program above, but without 'n' and 'r' commands. It prints the numbers on separate lines than the strings.

Works with: AT&T dc
[  plAP  plBP  lCP  1-dplAP  d2r >L]sL [Take one down, pass it around]sC[bottles of beer]sB[bottles of beer on the wall]sA99 lLx plAPplBPlCP1-p[bottle of beer on the wall]Pp[bottle of beer]P[Take it down, pass it around]P[no more bottles of beer on the wall]P

## DBL

;;===============================================================================;       Oringinal Author: Bob Welton ([email protected]);       Language: DIBOL or DBL;;       Modified to work with DBL version 4;       by Dario B.;===============================================================================          RECORD NRBOT,D2,99                  ;Default # of bottles to 99A2,     A2                                  PROC;-------------------------------------------------------------------------------         XCALL FLAGS (0007000000,1)      ;Suppress STOP message        OPEN (1,O,"TT:")                ;Open the terminal/display         DO FOREVER           BEGIN                A2=NRBOT,'ZX'                DISPLAY (1,A2," Bottles of Beer on the wall,",10)                 A2=NRBOT,'ZX'                DISPLAY (1,A2," Bottles of Beer,",10)                DISPLAY (1,"   Take one down, pass it around,",10)                 DECR NRBOT                      ;Reduce # of bottles by 1                IF (NRBOT.LE.1) EXITLOOP        ;If just 1 bottle left, get out                 A2=NRBOT,'ZX'                DISPLAY (1,A2," Bottles of Beer on the wall.",10,10)           END         A2=NRBOT,'ZX'        DISPLAY (1,A2," Bottle of Beer on the wall,",10,10)         A2=NRBOT,'ZX'        DISPLAY (1,A2," Bottle of Beer,",10)         DISPLAY (1,"   Take one down, pass it around,",10)        DISPLAY (1,"0 Bottles of Beer on the wall,",10)        DISPLAY (1,"0 Bottles of Beer,",10)        DISPLAY (1,"Go to the store and buy some more,",10)        DISPLAY (1,"99 Bottles of Beer on the wall,",10,10,10)        CLOSE 1        STOP

## Draco

proc nonrec bottles(byte b) void:    if b=0 then write("No more") else write(b) fi;    write(" bottle");    if b~=1 then write("s") ficorp; proc nonrec verse(byte v) void:    bottles(v);    writeln(" of beer on the wall,");    bottles(v);    writeln(" of beer,");    writeln("Take ",        if v=1 then "it" else "one" fi,        " down and pass it around");    bottles(v-1);    writeln(" of beer on the wall!\n");corp; proc nonrec main() void:    byte v;    for v from 99 downto 1 do verse(v) odcorp

## Dyalect

Translation of: Swift
for i in 99^-1..1 {    print("\(i) bottles of beer on the wall, \(i) bottles of beer.")    let next = if i == 1 {        "no"    } else {        (i - 1).toString()    }    print("Take one down and pass it around, \(next) bottles of beer on the wall.")}

## Dylan

Module: bottlesdefine 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);  endend method

## Déjà Vu

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

## DIBOL-11

 ;;=======================================================================================================;       Oringinal Author: Bob Welton ([email protected]);       Language: DIBOL or DBL;;       Modified to work with DEC DIBOL-11;       by Bill Gunshannon;======================================================================================================= RECORD MISC    NUMBOTTLES  ,D2,99                  ;Default # of bottles to 99 RECORD LINE1    ANUMBOTTLES, A2,   A32, " Bottles of Beer on the wall," RECORD LINE2BNUMBOTTLES, A2,    A32, " Bottles of Beer," RECORD LINE3CNUMBOTTLES, A2,    A32, " Bottles of Beer on the wall." RECORD LINE4DNUMBOTTLES, A2,    A32, " Bottle of Beer on the wall," RECORD LINE5ENUMBOTTLES, A2,    A32, " Bottle of Beer,"     .PROC    XCALL FLAGS (0007000000,1)          ;Suppress STOP message    OPEN (8,O:C,"TT:")                  ;Open the terminal/display    REPEAT        BEGIN        ANUMBOTTLES = NUMBOTTLES,'ZX'        WRITES (8,LINE1)        BNUMBOTTLES = NUMBOTTLES,'ZX'        WRITES (8,LINE2)        WRITES (8,"   Take one down, pass it around,")        DECR NUMBOTTLES                 ;Reduce # of bottles by 1        IF (NUMBOTTLES .LE. 1) EXITLOOP ;If just 1 bottle left, get out        CNUMBOTTLES = NUMBOTTLES,'ZX'        WRITES (8,LINE3)        WRITES (8," ")        END      DNUMBOTTLES = NUMBOTTLES,'ZX'      WRITES(8,LINE4)      WRITES (8," ")      ENUMBOTTLES = NUMBOTTLES,'ZX'      WRITES(8,LINE5)      WRITES (8,"   Take one down, pass it around,")      WRITES(8,"0 Bottles of Beer on the wall,")      WRITES(8,"0 Bottles of Beer,")      WRITES(8,"Go to the store and buy some more,")      WRITES(8,"99 Bottles of Beer on the wall,")     WRITES (8," ")    WRITES (8," ")    SLEEP 2    CLOSE 8    STOP.END

## E

def bottles(n) {  return switch (n) {    match ==0 { "No bottles" }    match ==1 { "1 bottle" }    match _   { $n bottles } }}for n in (1..99).descending() { println(${bottles(n)} of beer on the wall,${bottles(n)} of beer.Take one down, pass it around,${bottles(n.previous())} of beer on the wall.)}

## ECL

 Layout := RECORD  UNSIGNED1 RecID1;  UNSIGNED1 RecID2;  STRING30  txt;END;	Beers := DATASET(99,TRANSFORM(Layout,                              SELF.RecID1 := COUNTER,SELF.RecID2 := 0,SELF.txt := '')); Layout XF(Layout L,INTEGER C) := TRANSFORM  IsOneNext := L.RecID1-1 = 1;  IsOne := L.RecID1 = 1;  SELF.txt := CHOOSE(C,                     (STRING)(L.RecID1-1) + ' bottle'+IF(IsOneNext,'','s')+' of beer on the wall',                     'Take one down, pass it around',                     (STRING)(L.RecID1) + ' bottle'+IF(IsOne,'','s')+' of beer',                     (STRING)(L.RecID1) + ' bottle'+IF(IsOne,'','s')+' of beer on the wall','');  SELF.RecID2 := C;  SELF := L;END; Rev := NORMALIZE(Beers,5,XF(LEFT,COUNTER));OUTPUT(SORT(Rev,-Recid1,-RecID2),{txt},ALL);

## Egel

 import "prelude.eg"import "io.ego" using Systemusing IO def print_rhyme =    [ 0 ->        print "better go to the store, and buy some more\n"    | N ->        let _ = print N " bottles of beer on the wall\n" in        let _ = print N " bottles of beer\n" in        let _ = print "take one down, pass it around\n" in            print_rhyme (N - 1) ] def main = print_rhyme 99

## EGL

program TestProgram type BasicProgram {}     function main()        for (count int from 99 to 1 decrement by 1)            SysLib.writeStdout( bottleStr( count ) :: " of beer on the wall." );            SysLib.writeStdout( bottleStr( count ) :: " of beer." );            SysLib.writeStdout( "Take one down, pass it around." );            SysLib.writeStdout( bottleStr( count - 1) :: " of beer on the wall.\n");        end    end     private function bottleStr( count int in) returns( string )        case ( count )            when ( 1 )                return( "1 bottle" );            when ( 0 )                return( "No more bottles" );            otherwise                return( count :: " bottles" );        end    end	end

## Eiffel

 class	APPLICATION create	make feature {NONE} -- Initialization 	make		local			bottles: INTEGER		do			from				bottles := 99			invariant				bottles <= 99 and bottles >= 1			until				bottles = 1			loop				print (bottles)				print (" bottles of beer on the wall,%N")				print (bottles)				print (" bottles of beer.%N")				print ("Take one down, pass it around,%N")				bottles := bottles - 1				if bottles > 1 then					print (bottles)					print (" bottles of beer on the wall.%N%N")				end			variant				bottles			end			print ("1 bottle of beer on the wall.%N%N");			print ("No more bottles of beer on the wall,%N");			print ("no more bottles of beer.%N");			print ("Go to the store and buy some more,%N");			print ("99 bottles of beer on the wall.%N");		end end

An alternative version written using the across-loop construct.

 	output_lyrics			-- Output the lyrics to 99-bottles-of-beer.		local			l_bottles: LINKED_LIST [INTEGER]		do			create l_bottles.make			across (1 |..| 99) as ic loop l_bottles.force (ic.item) end			across l_bottles.new_cursor.reversed as ic_bottles loop				print (ic_bottles.item)				print (" bottles of beer on the wall, ")				print (ic_bottles.item)				print (" bottles of beer.%N")				print ("Take one down, pass it around, ")				if ic_bottles.item > 1 then					print (ic_bottles.item)					print (" bottles of beer on the wall.%N%N")				end			end			print ("1 bottle of beer on the wall.%N")			print ("No more bottles of beer on the wall, no more bottles of beer.%N")			print ("Go to the store and buy some more, 99 bottles of beer on the wall.%N")		end

## Ela

open list 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" map beer [99,98..0]

## Elena

ELENA 5.0 :

import system'routines;import extensions;import extensions'routines;import extensions'text; extension bottleOp{    bottleDescription()        = self.toPrintable() + (self != 1).iif(" bottles"," bottle");     bottleEnumerator() = new Variable(self).doWith:(n)    {        ^ new Enumerator        {            bool next() = n > 0;             get() = new StringWriter()                    .printLine(n.bottleDescription()," of beer on the wall")                    .printLine(n.bottleDescription()," of beer")                    .printLine("Take one down, pass it around")                    .printLine((n.reduce:1).bottleDescription()," of beer on the wall");             reset() {}             enumerable() = __target;        }    };} public program(){    var bottles := 99;     bottles.bottleEnumerator().forEach:printingLn}
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 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


## Elixir

defmodule Bottles do  def run do    Enum.each 99..1, fn idx ->      IO.puts "#{idx} bottle#{plural(idx)} of beer on the wall"      IO.puts "#{idx} bottle#{plural(idx)} of beer"      IO.puts "Take one down, pass it around"      IO.puts "#{idx - 1} bottle#{plural(idx-1)} of beer on the wall"      IO.puts ""    end  end   def plural(1), do: ""  def plural(num), do: "s"end Bottles.run

## Elm

module Main exposing (main) import Html  main =    List.range 1 100        |> List.reverse        |> List.map            (\n ->                let                    nString =                        String.fromInt n                     n1String =                        String.fromInt (n - 1)                in                [ nString ++ " bottles of beer on the wall"                , nString ++ " bottles of beer"                , "Take one down, pass it around"                , n1String ++ " bottles of beer on the wall"                ]                    |> List.map Html.text                    |> List.intersperse (Html.br [] [])                    |> Html.p []            )        |> Html.div []

## Emacs Lisp

 (let ((i 99)) 	      (while (> i 0)		(princ-list i " bottles of beer on the wall" "\n Take one down, pass it around") 		(setq i (1- i))))

## Erlang

-module(beersong).-export([sing/0]).-define(TEMPLATE_0, "~s of beer on the wall, ~s of beer.~nGo to the store and buy some more, 99bottles of beer on the wall.~n").-define(TEMPLATE_N, "~s of beer on the wall, ~s of beer.~nTake one down and pass it around, ~s ofbeer on the wall.~n~n"). create_verse(0)      -> {0, io_lib:format(?TEMPLATE_0, phrase(0))};create_verse(Bottle) -> {Bottle, io_lib:format(?TEMPLATE_N, phrase(Bottle))}. phrase(0)      -> ["No more bottles", "no more bottles"];phrase(1)      -> ["1 bottle", "1 bottle", "no more bottles"];phrase(2)      -> ["2 bottles", "2 bottles", "1 bottle"];phrase(Bottle) -> lists:duplicate(2, integer_to_list(Bottle) ++ " bottles") ++[integer_to_list(Bottle-1) ++ " bottles"]. bottles() -> lists:reverse(lists:seq(0,99)). sing() ->    lists:foreach(fun spawn_singer/1, bottles()),    sing_verse(99). spawn_singer(Bottle) ->    Pid = self(),     spawn(fun() -> Pid ! create_verse(Bottle) end). sing_verse(Bottle) ->    receive        {_, Verse} when Bottle == 0 ->            io:format(Verse);        {N, Verse} when Bottle == N ->            io:format(Verse),            sing_verse(Bottle-1)    after         3000 ->            io:format("Verse not received - re-starting singer~n"),            spawn_singer(Bottle),            sing_verse(Bottle)    end.

## Euphoria

Works with: Euphoria version 4.0.0
constant   bottles = "bottles",   bottle = "bottle" procedure beers (integer how_much)   sequence word1 = bottles, word2 = bottles   switch how_much do   case 2 then      word2 = bottle   case 1 then      word1 = bottle      word2 = bottle   end switch    printf (1,      "%d %s of beer on the wall \n" &      "%d %s of beer \n" &      "Take one down, and pass it around \n" &      "%d %s of beer on the wall \n\n",      { how_much, word1,        how_much, word1,        how_much-1, word2 }   )end procedure for a = 99 to 1 by -1 do   beers (a)end for
-- An alternate version include std/console.e sequence howmany = {"No more bottles","%d bottle","","s"} for beer = 99 to 1 by -1 do   display(   [1] bottles of beer on the wall,   [1] bottles of beer.   Take one down, drink it right down,   [2][3] of beer.   ,{beer,      sprintf(howmany[(beer>1)+1],beer-1),      howmany[(beer>2)+3]          })end for
-- yet another version: include std/console.e object stanza = {"[] bottles of beer on the wall,","[] bottles of beer,","take one down, and pass it around,"} object bottles = 99 loop do     display(stanza[1],bottles)    display(stanza[2],bottles)    display(stanza[3])    bottles -= 1     display(stanza[1]&"\n",{bottles})until bottles = 0 end loop

## F#

#lightlet rec bottles n =    let (before, after) = match n with                          | 1 -> ("bottle", "bottles")                          | 2 -> ("bottles", "bottle")                          | n -> ("bottles", "bottles")    printfn "%d %s of beer on the wall" n before    printfn "%d %s of beer" n before    printfn "Take one down, pass it around"    printfn "%d %s of beer on the wall\n" (n - 1) after    if n > 1 then        bottles (n - 1)

## Factor

USING: io kernel make math math.parser math.ranges sequences ; : bottle ( -- quot )    [        [            [                [ # " bottles of beer on the wall,\n" % ]                [ # " bottles of beer.\n" % ] bi            ] keep            "Take one down, pass it around,\n" %            1 - # " bottles of beer on the wall\n" %        ] " " make print    ] ; inline : last-verse ( -- )    "Go to the store and buy some more,"     "no more bottles of beer on the wall!" [ print ] [email protected] ; : bottles ( n -- )    1 [a,b] bottle each last-verse ; ! Usage: 99 bottles

## Falcon

for i in [99:1] > 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\n"end

A more robust version to handle plural/not plural conditions

## Fexl

 \suffix=(\n eq n 1 "" "s")\sing_count=(\n put [n " bottle" (suffix n) " of beer"])\sing_line1=(\n sing_count n say " on the wall")\sing_line2=(\n sing_count n nl)\sing==	(\n	le n 0 ();	sing_line1 n	sing_line2 n	say "Take one down, pass it around"	\n=(- n 1)	sing_line1 n	nl	sing n	)sing 3
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



## FOCAL

01.10 S N=9901.15 D 2;T " OF BEER ON THE WALL,",!01.20 D 2;T " OF BEER,",!01.24 S N=N-101.25 T "TAKE ";I (N),1.3,1.4,1.301.30 T "IT";G 1.501.40 T "ONE"01.50 T " DOWN AND PASS IT AROUND,",!01.60 D 2;T " OF BEER ON THE WALL!",!!01.70 I (N),1.8,1.1501.80 Q 02.01 C-PRINT N BOTTLE(S)02.10 I (N)2.2,2.2,2.302.20 T "NO MORE";G 2.402.30 D 302.40 T " BOTTLE";I (N-1)2.5,2.6,2.502.50 T "S"02.60 R 03.01 C-PRINT 2-DIGIT NUMBER IN N03.02 C-THIS IS NECESSARY BECAUSE T ALWAYS PREPENDS = TO NUMBERS03.10 S A=FITR(N/10);I (A),3.3,3.203.20 D 403.30 S A=N-FITR(N/10)*10;D 4 04.01 C-PRINT DIGIT IN A04.10 I (A-0),4.20,4.1104.11 I (A-1),4.21,4.1204.12 I (A-2),4.22,4.1304.13 I (A-3),4.23,4.1404.14 I (A-4),4.24,4.1504.15 I (A-5),4.25,4.1604.16 I (A-6),4.26,4.1704.17 I (A-7),4.27,4.1804.18 I (A-8),4.28,4.1904.19 T "9";R04.20 T "0";R04.21 T "1";R04.22 T "2";R04.23 T "3";R04.24 T "4";R04.25 T "5";R04.26 T "6";R04.27 T "7";R04.28 T "8";R

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

Version 2: create a beer language and write the program

DECIMAL: BOTTLES ( n -- )        DUP        CASE         1 OF    ." One more bottle " DROP ENDOF         0 OF    ." NO MORE bottles " DROP ENDOF                 . ." bottles "    \ DEFAULT CASE        ENDCASE ; : ,   [CHAR] , EMIT  SPACE 100 MS CR ;: .   [CHAR] . EMIT  300 MS  CR CR CR ; : OF       ." of "   ;     : BEER     ." beer " ;: ON       ." on "   ;     : THE      ." the "  ;: WALL     ." wall" ;      : TAKE     ." take " ;: ONE      ." one "  ;     : DOWN     ." down, " ;: PASS     ." pass " ;     : IT       ." it "   ;: AROUND   ." around" ; : POPONE    1 SWAP CR ;: DRINK     POSTPONE DO ; IMMEDIATE: ANOTHER   S" -1 +LOOP" EVALUATE ; IMMEDIATE: HOWMANY   S" I " EVALUATE ; IMMEDIATE: ONELESS   S" I 1- " EVALUATE ; IMMEDIATE: HANGOVER    ." :-("  CR QUIT ; : BEERS ( n -- )   \ Usage:  99 BEERS      POPONE      DRINK         HOWMANY BOTTLES OF BEER ON THE WALL ,         HOWMANY BOTTLES OF BEER ,         TAKE ONE DOWN PASS IT AROUND ,         ONELESS BOTTLES OF BEER ON THE WALL .      ANOTHER       HANGOVER ;

Forth Console Output

2 beers2 bottles of beer on the wall,2 bottles of beer ,take one down, pass it around,One more bottle of beer on the wall. One more bottle of beer on the wall,One more bottle of beer ,take one down, pass it around,No more bottles of beer on the wall.  ok

## Fortran

### F90 version

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

### MPI version

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

Usage:

mpif90 filename.f90
mpiexec -np 99 a.out

### Fortran 2003/2008 OOP version

Works with GNU gfortran 5.0.0 and Intel ifort 15.0.2

 module song_typedefs   implicit none    private ! all   public :: TBottles    type, abstract :: TContainer      integer :: quantity   contains      ! deferred method i.e. abstract method =  must be overridden in extended type      procedure(take_one), deferred, pass :: take_one      procedure(show_quantity), deferred, pass :: show_quantity   end type TContainer     abstract interface      subroutine  take_one(this)         import TContainer         implicit none         class(TContainer) :: this      end subroutine take_one      subroutine  show_quantity(this)         import TContainer         implicit none         class(TContainer) :: this      end subroutine show_quantity   end interface    ! extended derived type   type, extends(TContainer) :: TBottles   contains      procedure, pass :: take_one => take_one_bottle      procedure, pass :: show_quantity => show_bottles      final :: finalize_bottles   end type TBottles  contains    subroutine  show_bottles(this)      implicit none      class(TBottles) :: this      ! integer :: show_bottles      character(len=*), parameter :: bw0 = "No more bottles of beer on the wall,"      character(len=*), parameter :: bwx = "bottles of beer on the wall,"      character(len=*), parameter :: bw1 = "bottle of beer on the wall,"      character(len=*), parameter :: bb0 = "no more bottles of beer."      character(len=*), parameter :: bbx = "bottles of beer."      character(len=*), parameter :: bb1 = "bottle of beer."      character(len=*), parameter :: fmtxdd = "(I2,1X,A28,1X,I2,1X,A16)"      character(len=*), parameter :: fmtxd = "(I1,1X,A28,1X,I1,1X,A16)"      character(len=*), parameter :: fmt1 = "(I1,1X,A27,1X,I1,1X,A15)"      character(len=*), parameter :: fmt0 = "(A36,1X,A24)"       select case (this % quantity)       case (10:)         write(*,fmtxdd) this % quantity, bwx, this % quantity, bbx       case (2:9)         write(*,fmtxd) this % quantity, bwx, this % quantity, bbx       case (1)         write(*,fmt1) this % quantity, bw1, this % quantity, bb1       case (0)         write(*,*)         write(*,fmt0) bw0, bb0       case default         write(*,*)"Warning!  Number of bottles exception, error 42. STOP"         stop      end select      !    show_bottles = this % quantity   end subroutine show_bottles    subroutine  take_one_bottle(this) ! bind(c, name='take_one_bottle')      implicit none      class(TBottles) :: this      ! integer :: take_one_bottle      character(len=*), parameter :: t1 = "Take one down and pass it around,"      character(len=*), parameter :: remx = "bottles of beer on the wall."      character(len=*), parameter :: rem1 = "bottle of beer on the wall."      character(len=*), parameter :: rem0 = "no more bottles of beer on the wall."      character(len=*), parameter :: fmtx = "(A33,1X,I2,1X,A28)"      character(len=*), parameter :: fmt1 = "(A33,1X,I2,1X,A27)"      character(len=*), parameter :: fmt0 = "(A33,1X,A36)"       this % quantity = this % quantity -1       select case (this%quantity)       case (2:)         write(*,fmtx) t1, this%quantity, remx       case (1)         write(*,fmt1) t1, this%quantity, rem1       case (0)         write(*,fmt0) t1, rem0       case (-1)         write(*,'(A66)') "Go to the store and buy some more, 99 bottles of beer on the wall."       case default         write(*,*)"Warning!  Number of bottles exception, error 42. STOP"         stop      end select    end subroutine take_one_bottle    subroutine  finalize_bottles(bottles)      implicit none      type(TBottles) :: bottles   ! here can be more code   end subroutine finalize_bottles end module song_typedefs !-----------------------------------------------------------------------!Main program!-----------------------------------------------------------------------program    bottles_song   use song_typedefs   implicit none   integer, parameter :: MAGIC_NUMBER = 99   type(TBottles), target :: BTLS    BTLS = TBottles(MAGIC_NUMBER)    call make_song(BTLS)  contains    subroutine make_song(bottles)      type(TBottles) :: bottles      do while(bottles%quantity >= 0)         call bottles%show_quantity()         call bottles%take_one()      enddo   end subroutine make_song end program bottles_song

## Frege

Works with: Frege version 3.21.586-g026e8d7
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"

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

 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"

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

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( [email protected](13 | 15) ) = suffix( alt(n%10), 'teen' )  number( 20 ) = 'twenty'  number( [email protected](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) )

## FutureBasic

 include "NSLog.incl" NSUInteger  iCFStringRef a, b, c a = @" bottles of beer on the wall,\n"b = @" bottles of beer.\n"c = @"Take one down, pass it around,\n" for i = 99 to 1 step -1NSLog( @"%ld%@%ld%@%@%ld%@\n", i, a, i, b, c, i -1, a )next HandleEvents

## Gambas

Implementation of the code '99 bottles of beer' written in Visual Basic. Code tested in Gambas 3.15.2

' Gambas module file Public Const bottlesofbeer As String = " bottles of beer."Public Const onthewall As String = " on the wall."Public Const takeonedown As String = "Take one down, pass it around."Public Const onebeer As String = "1 bottle of beer" Public Sub Main()   Dim bottles As Byte   For bottles = 99 To 3 Step -1    Print CStr(bottles) & bottlesofbeer & onthewall    Print CStr(bottles) & bottlesofbeer    Print takeonedown    Print CStr(bottles - 1) & bottlesofbeer & onthewall    Print  Next   Print "2" & bottlesofbeer & onthewall  Print "2" & bottlesofbeer  Print takeonedown  Print onebeer & onthewall  Print   Print onebeer & onthewall  Print onebeer  Print takeonedown  Print "No more" & bottlesofbeer & onthewall  Print   Print "No" & bottlesofbeer & onthewall  Print "No" & bottlesofbeer  Print "Go to the store, buy some more."  Print "99" & bottlesofbeer & onthewall End

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

## Genie

[indent=4]def plural(n:uint):string    return (n == 1) ? "" : "s"def no(n:uint):string    return (n == 0) ? "No" : n.to_string()init    bottles:uint = 99;    do        print "%u bottle%s of beer on the wall", bottles, plural(bottles)        print "%u bottle%s of beer", bottles, plural(bottles)        print "Take one down, pass it around"        --bottles        print "%s bottle%s of beer on the wall\n", no(bottles), plural(bottles)    while bottles != 0
Output:
prompt$valac 99bottles.gs prompt$ ./99bottles | tail -10
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
No bottles of beer on the wall

## gnuplot

if (!exists("bottles")) bottles = 99print 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 - 1print sprintf("%i bottles of beer on the wall", bottles)print ""if (bottles > 0) reread

## Go

### No sense of humor

package main import "fmt" func main() {	bottles := func(i int) string {		switch i {		case 0:			return "No more bottles"		case 1:			return "1 bottle"		default:			return fmt.Sprintf("%d bottles", i)		}	} 	for i := 99; i > 0; i-- {		fmt.Printf("%s of beer on the wall\n", bottles(i))		fmt.Printf("%s of beer\n", bottles(i))		fmt.Printf("Take one down, pass it around\n")		fmt.Printf("%s of beer on the wall\n", bottles(i-1))	}}

### Typoglycemic

With code from RC tasks Number names, Knuth shuffle.

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 taskfunc 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 99func 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, " ")}
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
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.

-- -- 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".}

## Golfscript

### Single Print Version

Uses a single print algorithm for all four lines. Handles cardinality on bottles, uses 'No more' instead of 0.

298.downto(2) {    def (m,d) = [it%3,(int)it/3]    print "${m==1?'\n':''}${d?:'No more'} bottle${d!=1?'s':''} of beer" + "${m?' on the wall':'\nTake one down, pass it around'}\n"}

### Bottomless Beer Solution

Using more closures to create a richer lyrical experience.

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)// }

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

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]

We haven't drank all of the bottles at this point, but we can keep going, if we want.

## Halon

$plural = "s";$x = 99;while ($x > 0) { echo "$x bottle$plural of beer on the wall"; echo "$x bottle$plural of beer"; echo "Take one down, pass it around";$x -= 1;    if ($x == 1)$plural = "";    if ($x > 0) echo "$x bottle$plural of beer on the wall\n"; else echo "No more bottles of beer on the wall!";} ## Haskell #### Brevity A relatively concise solution: 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" #### List comprehension As a list comprehension: 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"

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.

## hexiscript

fun bottles amount beverage location  let bottle " bottles of "  if   amount = 0; let amount "No more"  elif amount = 1; let bottle " bottle of "; endif  return amount + bottle + beverage + " " + locationendfun fun take amount location  return "Take " + amount + " " + locationendfun fun pass entity destination  return ", pass " + entity + " " + destinationendfun let amount 99while amount > 0  println bottles amount "beer" "on the wall"  println bottles amount "beer" ""  println take "one" "down" + pass "it" "around"  println bottles (--amount) "beer" "on the wall\n"endwhile

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

## HolyC

The default is 99 bottles, but it can be modified by the parameter.

U0 BottlesOfBeer (I64 initial=99) {	// This is made I64 rather than U64	// Because, a U64 would overflow	// At the end of the loop, thus it would loop forever (i-- would be 0-1 so it overflows and is always  greater than or equal to 0)	I64 i = initial; 	for (; i >= 0; i--) {		if (i == 1) {			// Just a string on it's own will pass it to an inbuilt HolyC function that puts it to terminal			"1 Bottle of Beer on the wall, 1 bottle of beer.\n";			"Take one down and pass it around, no more bottles of beer on the wall.\n";		} else if (i == 0) {			"No more bottles of beer on the wall, no more bottles of beer.\n";			"Go to the store and buy some more, 99 bottles of beer on the wall.\n";		} else {			"%d bottles of beer on the wall, %d bottles of beer.\n",i,i;			"Take one down and pass it around, %d bottle",(i-1);			// Only add the s if it's not 1			if ((i-1) != 1) {				"s";			} 			" of beer on the wall.\n";		}	}} // Calls the function, which goes to the default parametersBottlesOfBeer;

## Huginn

#! /bin/shexec huginn --no-argv -E "${0}" "${@}"#! huginn import Algorithms as algo; main() {	x = "{} bottle{} of beer on the wall,\n"		"{} bottle{} of beer.\n"		"Take one down, pass it around,\n"		"{} bottle{} of beer on the wall.\n\n";	for ( n : algo.range( 99, 0, -1 ) ) {		bot = n > 0 ? n : "No";		plu = n != 1 ? "s" : "";		print( x.format( bot, plu, bot, plu, n > 1 ? n - 1 : "No", n != 2 ? "s" : "" ) );	}	print(		"No bottles of beer on the wall,\n"		"No bottles of beer.\n"		"Go to the store, buy some more,\n"		"99 bottles of beer on the wall.\n"	);	return ( 0 );}

## Icon and Unicon

The default is 99 bottles, but you can change this on the command line for really long trips...

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

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

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:

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

I found the above example very helpful but overdone. This is a more simple version:

Pro bottles_noloop2    n_bottles=99    b1 = reverse(SINDGEN(n_bottles,START=1))    b2= reverse(SINDGEN(n_bottles))    wallT=replicate(' bottles of beer on the wall.', n_bottles)    wallT2=replicate(' bottles of beer.', n_bottles)    takeT=replicate('Take one down, pass it around,', n_bottles)    print, b1+wallT+string(10B)+b1+wallT2+string(10B)+takeT+string(10B)+b2+wallT+string(10B)End

## Idris

 beerSong : Fin 100 -> StringbeerSong 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)

## Inform 6

[ 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);];

## Inform 7

### Programmatic solution

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.

### World model solution

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

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

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

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

## J

As posted at the J wiki

bob =: ": , ' bottle' , (1 = ]) }. 's of beer'"_bobw=: bob , ' on the wall'"_beer=: bobw , ', ' , bob , '; take one down and pass it around, ' , [email protected]<:beer"0 >:i.-99
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.

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

Optimized for speed and few I/O operations

public class Beer {    public static void main(String[] args) {        int bottles = 99;        StringBuilder sb = new StringBuilder();        String verse1 = " bottles of beer on the wall\n";        String verse2 = " bottles of beer.\nTake one down, pass it around,\n";        String verse3 = "Better go to the store and buy some more.";         while (bottles > 0)            sb.append(bottles).append(verse1).append(bottles).append(verse2).append(--bottles).append(verse1).append("\n");         System.out.println(sb.append(verse3));    }}

Recursive

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

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

import java.awt.BorderLayout;import java.awt.event.ActionEvent;import javax.swing.JButton;import javax.swing.JFrame;import javax.swing.JOptionPane;import javax.swing.JTextArea; public class Beer extends JFrame {    private int x;    private JTextArea text;     public static void main(String[] args) {        new Beer().setVisible(true);    }     public Beer() {        x = 99;         JButton take = new JButton("Take one down, pass it around");        take.addActionListener(this::onTakeClick);         text = new JTextArea(4, 30);        text.setText(x + " bottles of beer on the wall\n" + x + " bottles of beer");        text.setEditable(false);         setLayout(new BorderLayout());        add(text, BorderLayout.CENTER);        add(take, BorderLayout.PAGE_END);        pack();        setLocationRelativeTo(null);        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);    }     private void onTakeClick(ActionEvent event) {        JOptionPane.showMessageDialog(null, --x + " bottles of beer on the wall");        text.setText(x + " bottles of beer on the wall\n" + x + " bottles of beer");        if (x == 0) {            dispose();        }    }}

## JavaScript

### ES3-5

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

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  ${beer-1} bottles of beer on the wall; console.log(verse); beer--;} ### Functional / Recursive var bottles = 99;var songTemplate = "{X} bottles of beer on the wall \n" + "{X} bottles of beer \n"+ "Take one down, pass it around \n"+ "{X-1} bottles of beer on the wall \n"; function song(x, txt) { return txt.replace(/\{X\}/gi, x).replace(/\{X-1\}/gi, x-1) + (x > 1 ? song(x-1, txt) : "");} console.log(song(bottles, songTemplate)); ### Other Examples More skilled solution "one-liner" with grammar check Comment: This being a "one-liner" is arguable. The author has chosen not to put a line break after the declaration of the beer variable. By using the authors definition, most of the other solutions could pass as a "one-liner". // Line breaks are in HTMLvar beer; while ((beer = typeof beer === "undefined" ? 99 : beer) > 0) document.write( beer + " bottle" + (beer != 1 ? "s" : "") + " of beer on the wall<br>" + beer + " bottle" + (beer != 1 ? "s" : "") + " of beer<br>Take one down, pass it around<br>" + (--beer) + " bottle" + (beer != 1 ? "s" : "") + " of beer on the wall<br>" ); Legitimate "one-liner" with grammar check, using declarative methods. Array.from(Array(100).keys()).splice(1).reverse().forEach(n => console.log(${n} bottle${n !== 1 ? 's' : ''} of beer on the wall\n${n} bottle${n !== 1 ? 's' : ''} of beer\nTake one down, pass it around\n${n - 1} bottle${n - 1 !== 1 ? 's' : ''} of beer on the wall\n\n)); Object Oriented function Bottles(count) { this.count = count || 99;} Bottles.prototype.take = function() { var verse = [ this.count + " bottles of beer on the wall,", this.count + " bottles of beer!", "Take one down, pass it around", (this.count - 1) + " bottles of beer on the wall!" ].join("\n"); console.log(verse); this.count--;}; Bottles.prototype.sing = function() { while (this.count) { this.take(); }}; var bar = new Bottles(99);bar.sing(); An alternative version: function bottleSong(n) { if (!isFinite(Number(n)) || n == 0) n = 100; var a = '%% bottles of beer', b = ' on the wall', c = 'Take one down, pass it around', r = '<br>' p = document.createElement('p'), s = [], re = /%%/g; while(n) { s.push((a+b+r+a+r+c+r).replace(re, n) + (a+b).replace(re, --n)); } p.innerHTML = s.join(r+r); document.body.appendChild(p);} window.onload = bottleSong; ## Joy LIBRA _beerlib == true ; HIDE beer == "of beer " putchars ; wall == "on the wall" putchars ; take1 == "Take one down and pass it around, " putchars ; dup3 == dup dup dup ; comma == ", " putchars ; period == '. putch ; bottles == [dup small] [ [null] [pop "no more bottles " putchars] [put "bottle " putchars] ifte] [put "bottles " putchars] ifte ; sing-verse == dup3 bottles beer wall comma bottles beer ".\n" putchars take1 1 - bottles beer wall period newline newline ; sing-verse-0 == "No more bottles of beer on the wall, no more bottles of beer\n" putchars "Go to the store and buy some more, " putchars 99 bottles pop beer wall period newline ; IN (* n -- *) sing-verses == [null] [sing-verse-0] [sing-verse 1 -] tailrec . ## jq Minimalist: 99| (. - range(0;.+1) )| "\(.) bottles of beer on the wall\(.) bottles of beerTake one down, pass it around\(.) bottles of beer on the wall" Output: $ jq -n -r -f 99_bottles.jq... 2 bottles of beer on the wall2 bottles of beerTake one down, pass it around2 bottles of beer on the wall 1 bottles of beer on the wall1 bottles of beerTake one down, pass it around1 bottles of beer on the wall 0 bottles of beer on the wall0 bottles of beerTake one down, pass it around0 bottles of beer on the wall

Variant:

def sing:  def s: if . == 1 then "" else "s" end;  def bottles:    if . == 0 then "No more"    else "\(.)"    end + " bottle\(s)";  (. - range(0;.+1) )  | "\(bottles) of beer on the wall\(bottles) of beerTake one down, pass it around\(bottles) of beer on the wall."; $bottles | tonumber | sing Output: $ jq -r --arg bottles 99 -f 99_bottles_variant.jq...2 bottles of beer on the wall2 bottles of beerTake one down, pass it around2 bottles of beer on the wall. 1 bottle of beer on the wall1 bottle of beerTake one down, pass it around1 bottle of beer on the wall. No more bottles of beer on the wallNo more bottles of beerTake one down, pass it aroundNo more bottles of beer on the wall.

## Jsish

/* 99 Bottles, in Jsish */function plural(n:number):string { return (bottles == 1) ? "" : "s"; }function no(n:number):string { return (bottles == 0) ? "No" : n.toString(); } var bottles = 99;do {    printf("%d bottle%s of beer on the wall\n", bottles, plural(bottles));    printf("%d bottle%s of beer\n", bottles, plural(bottles));    puts("Take one down, pass it around");    bottles--;    printf("%s bottle%s of beer on the wall\n\n", no(bottles), plural(bottles));} while (bottles > 0);

one-liner

## MACRO-11

 ;;          99 BOTTLES OF BEER;          WRITTEN  BY:  BILL GUNSHANNON;            .MCALL  .PRINT .EXIT            .RADIX  10   MESG1:CNUM1:     .ASCII  "  "           .ASCII  " BOTTLES OF BEER ON THE WALL, "CNUM2:     .ASCII  "  "           .ASCII  " BOTTLES OF BEER."<13><10>           .ASCII  "TAKE ONE DOWN AND PASS IT AROUND, "CNUM3:     .ASCII  "  "           .ASCIZ  " BOTTLES OF BEER ON THE WALL."<13><10><10> MESG2:     .ASCII  " 2 BOTTLES OF BEER ON THE WALL, "           .ASCII  " 2 BOTTLES OF BEER."<13><10>           .ASCII  "TAKE ONE DOWN AND PASS IT AROUND, "           .ASCIZ  " 1 BOTTLE OF BEER ON THE WALL."<13><10><10> MESG3:     .ASCII  " 1 BOTTLE OF BEER ON THE WALL, "           .ASCII  " 1 BOTTLE OF BEER."<13><10>           .ASCII  "TAKE ONE DOWN AND PASS IT AROUND, "           .ASCIZ  "NO MORE BOTTLES OF BEER ON THE WALL."<13><10><10> MESG4:     .ASCII  "NO MORE BOTTLES OF BEER ON THE WALL, "           .ASCII  "NO MORE BOTTLES OF BEER."<13><10>           .ASCII  "GO TO THE STORE AND BUY SOME MORE, "           .ASCIZ  "99 BOTTLES OF BEER ON THE WALL."<13><10><10>            .EVEN COUNT1:    .WORD   99      ;  STARTING NUMBER OF BOTTLESPV:        .WORD   10.,1,  ;  POSITION VALUES FOR 2 DIGITS  START:           MOV     COUNT1, R0           MOV     R0, R5           DEC     R5AGAIN:            MOV     #CNUM1, R1 ;       CONVERT NUMBER OF BOTTLES TO ASCII FOR THE FIRST FIELD            MOV     R0,-(SP)           MOV     R1,-(SP)           MOV     R2,-(SP)           MOV     R3,-(SP)           MOV     R4,-(SP)           MOV     R5,-(SP)            MOV     #PV, R3           MOV     #2, R2A1$: MOV #-1,R4A2$:       INC     R4           SUB     (R3), R0           BCC     A2$ADD (R3)+, R0 ADD #48, R4 MOVB R4, (R1)+A21$:      SOB     R2, A1$; REMOVE LEADING ZERO - JUST LOOKS BETTER THAT WAY MOV #CNUM1, R1 CMPB (R1), #48 BNE CONT1 MOVB #32, (R1)CONT1: MOV #CNUM2, R0 ; MOVE THE ASCII NUMBER TO FIELD TWO RATHER THAN COMPUTING IT AGAIN MOVB (R1)+, (R0)+ MOVB (R1), (R0) MOV R5, R0 MOV #CNUM3, R1 ; CONVERT NUMBER OF BOTTLES TO ASCII FOR THE THIRD FIELD MOV #PV, R3 MOV #2, R2B1$:       MOV     #-1,R4B2$: INC R4 SUB (R3), R0 BCC B2$           ADD     (R3)+, R0           ADD     #48, R4           MOVB    R4, (R1)+B21$: SOB R2, B1$ ;   REMOVE LEADING ZERO - JUST LOOKS BETTER THAT WAY            MOV     #CNUM3, R1           CMPB    (R1), #48           BNE     CONT2           MOVB    #32, (R1)CONT2:             MOV     (SP)+,R5           MOV     (SP)+,R4           MOV     (SP)+,R3           MOV     (SP)+,R2           MOV     (SP)+,R1           MOV     (SP)+,R0  ;       HANDLE SPECIAL GRAMMER CASES            CMP     R0, #2           BNE     ONE           .PRINT  #MESG2           BR      DONEONE:       CMP     R0, #1           BNE     GREATER           .PRINT  #MESG3           BR      DONEGREATER:           .PRINT  #MESG1 DONE: ;        DECREMENT THE COUNT AND START AGAIN            MOV     R5, R0           DEC     R5           TST     R0           BNE     AGAIN ;    OUT OF BEER, SEND THEM TO THE STORE            .PRINT  #MESG4 ;   CLEAN UP AND GO BACK TO KMON            .EXIT             .END     START

            NORMAL MODE IS INTEGER             BOTLES = 99VERSE       WALL.(BOTLES)            BOTL.(BOTLES)            PRINT FORMAT TKDWN            BOTLES = BOTLES - 1            WALL.(BOTLES)            PRINT FORMAT EMPTY            WHENEVER BOTLES .G. 0, TRANSFER TO VERSE             INTERNAL FUNCTION(B)            ENTRY TO BOTL.            WHENEVER B .E. 1               PRINT FORMAT ONEBTL            OTHERWISE               PRINT FORMAT BBTL,B            END OF CONDITIONAL            FUNCTION RETURN            END OF FUNCTION             INTERNAL FUNCTION(B)            ENTRY TO WALL.            WHENEVER B .E. 0               PRINT FORMAT NOMORE            OR WHENEVER B .E. 1               PRINT FORMAT ONEOTW            OTHERWISE               PRINT FORMAT BBOTW,B            END OF CONDITIONAL            FUNCTION RETURN            END OF FUNCTION             VECTOR VALUES BBOTW  = $I2,S1,27HBOTTLES OF BEER ON THE WALL*$            VECTOR VALUES BBTL   = $I2,S1,15HBOTTLES OF BEER*$            VECTOR VALUES TKDWN  = $32HTAKE ONE DOWN AND PASS IT AROUND*$            VECTOR VALUES ONEOTW = $S1,29H 1 BOTTLE OF BEER ON THE WALL*$            VECTOR VALUES ONEBTL = $S1,17H 1 BOTTLE OF BEER*$            VECTOR VALUES NOMORE = $35HNO MORE BOTTLES OF BEER ON THE WALL*$            VECTOR VALUES EMPTY  = $*$            END OF PROGRAM

## make

### BSD make

Library: jot
Works with: BSD make

## MAXScript

escapeEnable  = true resetMaxFile #noPromptviewport.setType #view_topmax tool maximizeviewport.SetRenderLevel #smoothhighlightsdelay = 1.6a = text size:30a.wirecolor = whitetheMod = extrude()addModifier a theMod for i in 99 to 1 by -1 do -- this will iterate through 99 times use the escape key to terminate.(    a.text = (i as string + " bottles of beer on the wall")    redrawViews()    sleep delay     a.text = (i as string + " bottles of beer")    redrawViews()    sleep delay     a.text = "Take one down, pass it around"    redrawViews()    sleep delay     a.text = ((i-1) as string + " bottles of beer on the wall")    redrawViews()    sleep delay )

### A one-line version

Since MAXscript is an expression based language (everything returns a value), it is relatively easy to write long expressions that are only one line long. the following single-line snippet (broken for clarity on the webpage) produces a grammatically correct printout of the song.

for i = 99 to 1 by -1 do (print (i as string + (if i == 1 then " bottle" else " bottles") + " of beer on the wall\n" + i as string +\ (if i == 1 then " bottle" else " bottles") + " of beer\nTake one down, pass it around\n" + (i - 1) as string + (if i - 1 == 1 then "\ bottle" else " bottles") + " of beer on the wall\n" + (if i - 1 == 0 then "\nno more beer" else "")))

## Mercury

 % file: beer.m% author:%   Fergus Henderson <[email protected]> Thursday 9th November 1995% Re-written with new syntax standard library calls:%   Paul Bone <[email protected]> 2015-11-20%% This beer song is more idiomatic Mercury than the original, I feel bad% saying that since Fergus is a founder of the language. :- module beer.:- interface.:- import_module io. :- pred main(io::di, io::uo) is det. :- implementation. :- import_module int.:- import_module list.:- import_module string. main(!IO) :-    beer(99, !IO). :- pred beer(int::in, io::di, io::uo) is det. beer(N, !IO) :-    io.write_string(beer_stanza(N), !IO),    ( N > 0 ->        io.nl(!IO),        beer(N - 1, !IO)    ;        true    ). :- func beer_stanza(int) = string. beer_stanza(N) = Stanza :-    ( N = 0 ->        Stanza = "Go to the store and buy some more!\n"    ;        NBottles = bottles_line(N),        N1Bottles = bottles_line(N - 1),        Stanza =            NBottles ++ " on the wall.\n" ++            NBottles ++ ".\n" ++            "Take one down, pass it around,\n" ++            N1Bottles ++ " on the wall.\n"    ). :- func bottles_line(int) = string. bottles_line(N) =    ( N = 0 ->        "No more bottles of beer"    ; N = 1 ->        "1 bottle of beer"    ;        string.format("%d bottles of beer", [i(N)])    ). 

## min

Works with: min version 0.19.3

## N/t/roff

### Classical version (compatible with classical Bell Lab's TROFF)

Subroutine L1 calls upon itself recursively.

Works with: All TROFF
.nr BS 99 1.de L1.ie \\n(BS>1 \{ \\\n(BS bottles of beer on the wall,\\n(BS bottles of beer.\c\}.el \{ \\\n(BS bottle of beer on the wall,\\n(BS bottle of beer.\c\}Take one down, pass it around,\\n-(BS bottles of beer on the wall. .if \\n(BS>0 .L1...nf.L1.fi

### New version (compatible only with GNU TROFF)

Instead of recursion, a while construct can be used instead, to achieve the same results. Technically, the program runs differently.

Works with: GNU TROFF version 1.22.2
.nr beers 99 1.nf.while \n[beers]>0 \{ \.ie \n[beers]>1 \{ \\n[beers] bottles of beer on the wall,\n[beers] bottles of beer.\c\} \" ie \n[beers]>1.el \{ \\n[beers] bottle of beer on the wall,\n[beers] bottle of beer.\c\} \" elTake one down, pass it around,\n-[beers] bottles of beer on the wall.\} \" while \n[beers]>0.fi

## Nanoquery

Translation of: Ursa
//// 99 bottles of beer// for bottles in range(99, 1, -1)	bottlestr = "" 	if bottles = 1		bottlestr = "bottle"	else		bottlestr = "bottles"	end if 	println (bottles + " " + bottlestr + " of beer on the wall")	println (bottles + " " + bottlestr + " of beer")	println "Take one down, pass it around." 	if !(bottles = 2)		println (bottles - 1 + " bottles of beer on the wall.\n")	else		println "1 bottle of beer on the wall.\n"	end ifend for

## NASL

bottles = 99;repeat {  display(bottles, ' bottles of beer on the wall\n');  display(bottles, ' bottles of beer\n');  display('Take one down, pass it around\n');  display(--bottles, ' bottles of beer on the wall\n\n');} until bottles < 1;

## Neko

/** <doc> <h3>Rosetta Code, 99 bottles of beer on the wall, in Neko</h3>  <pre> Tectonics:   nekoc 99bottles.neko   neko 99bottles </pre> </doc>**/ var message = " of beer on the wall\n";var beers = 99; var plural = function(n) {  return if (n == 1) " bottle" else " bottles";} var nonesome = function(n) {  return if (n > 0) n else "No more";} while (beers > 0) {  $print(nonesome(beers), plural(beers), message);$print(nonesome(beers), plural(beers), " of beer\n");  $print("Take one down, pass it around\n"); beers -= 1;$print(nonesome(beers), plural(beers), message);  if (beers > 0) $print("\n");} Output: prompt$ nekoc 99bottles.neko

## NetRexx

 beer = "bottles of beer on the wall"removeOne = "Take one down, pass it arround,"say 99 beer","say 99 beer.subword(1,3)","loop i = 98 to 2 by -1  say removeOne  say i beer"."  say  say i beer","  say i beer.subword(1,3)","endlastCall = "bottle" beer.delword(1,1)say removeOnesay i lastCall"."saysay i lastCall","say i lastCall.subword(1,3)","say removeOnesay "No more" beer 

## Nial

line is fork [  0=, 'No more bottles of beer' first,  1=, 'One bottle of beer' first,   link [string,' bottles of beer' first]] verse is link [  line, ' on the wall, ' first,line,  '. Take it down and pass it around, ' first,  line (-1+),'on the wall. ' first] bottles is iterate (write verse) reverse count

## Night

null bottles(int x) {  if(x == 1) {    print("1 bottle of beer on the wall,\n");    print("1 bottle of beer,\n");    print("Take it down, pass it around,\n");    print("No more bottles of beer.\n");  }  else {    print(x);    print(" bottles of beer on the wall,\n");    print(x);    print(" bottles of beer,\n");    print("Take one down, pass it around,\n");    print(x - 1);    print(" bottles of beer on the wall,");    bottles(x-1);  }}bottles(1);

This code should work according to the docs, but due to a few bugs in the current implementation it doesn't.

## OASYS

 class player {} int count property int dummy method quit verbs {{quit}} {  quit} method beer verbs {{beer}} {  count = 99  while count {    print count    print " bottles of beer on the wall.\n"    print count    print " bottles of beer.\nTake one down and pass it around,\n"    count = count - 1    if count {      print count      print " bottles of beer on the wall.\n\n"    }  }  print "No more bottles of beer on the wall.\n"} method init {  player = create player  print "Type 'beer' for beer.\nType 'quit' to quit.\n"} 

## Oberon-2

MODULE b99; IMPORT  Out; VAR     nr      : INTEGER; BEGIN  nr := 99;  REPEAT    Out.Int (nr, 4);    Out.String (" bottles of beer on the wall");    Out.Ln;    Out.Int (nr, 4);    Out.String (" bottles of beer");    Out.Ln;    Out.String ("Take one down, pass it around");    Out.Ln;    DEC (nr);    Out.Int (nr, 4);    Out.String (" bottles of beer on the wall");    Out.Ln;    Out.Ln  UNTIL nr = 0END b99.

## Objeck

 class Bottles {  function : Main(args : String[]) ~ Nil {    bottles := 99;    do {      "{$bottles} bottles of beer on the wall"->PrintLine(); "{$bottles} bottles of beer"->PrintLine();      "Take one down, pass it around"->PrintLine();      bottles--;      "{$bottles} bottles of beer on the wall"->PrintLine(); } while(bottles > 0); }} ## Objective-C #import <Foundation/Foundation.h> int main(){ @autoreleasepool { int bottles = 99; do { NSLog(@"%i bottles of beer on the wall\n", bottles); NSLog(@"%i bottles of beer\n", bottles); NSLog(@"Take one down, pass it around\n"); NSLog(@"%i bottles of beer on the wall\n\n", --bottles); } while (bottles > 0); } return 0;} ## OCaml ### For-loop for n = 99 downto 1 do Printf.printf "%d bottles of beer on the wall\n" n; Printf.printf "%d bottles of beer\n" n; Printf.printf "Take one down, pass it around\n"; Printf.printf "%d bottles of beer on the wall\n\n" (pred n);done ### Recursive Recursive version that handles plurals. let verse n = let line2 = function | 0 -> "No more bottles of beer" | 1 -> "1 bottle of beer" | n -> string_of_int n ^ " bottles of beer" in let line1or4 y = line2 y ^ " on the wall" in let line3 = function | 1 -> "Take it down, pass it around" | _ -> "Take one down, pass it around" in line1or4 n ^ "\n" ^ line2 n ^ "\n" ^ line3 n ^ "\n" ^ line1or4 (n-1) ^ "\n";; let rec beer n = print_endline (verse n); if n > 1 then beer (n-1);; beer 99;; ### Monadic Monadic version, expressing actions which evolve the program state and log output. Special cases and grammar rules are handled. (* A basic "Writer" monoid with emit *)module Writer = struct type 'a t = 'a * string let ( >>= ) (x,s) f = let (y,s') = f x in (y, s ^ s') let return x = (x,"") let emit (x,s) = print_string s; xend (* Utility functions for handling strings and grammar *)let line s = (String.capitalize s) ^ ".\n"let count = function 0 -> "no more" | n -> string_of_int nlet plural = function 1 -> "" | _ -> "s"let specify = function 1 -> "it" | _ -> "one"let bottles n = count n ^ " bottle" ^ plural n ^ " of beer" (* Actions, expressed as an int * string, for Writer *)let report n = (n, line (bottles n ^ " on the wall, " ^ bottles n))let take n = (n-1, "Take " ^ specify n ^ " down and pass it around")let summary n = (n, ", " ^ bottles n ^ " on the wall.\n\n")let shop = (99, "Go to the store and buy some more") let rec verse state = Writer.(state >>= report >>= function 0 -> shop >>= summary (* ends here *) | n -> take n >>= summary |> verse)let sing start = Writer.(emit (verse (return start))) Output for initial beer-count of two: # sing 2;;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 it 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. - : int = 99 Note the output value is 99... reflecting the state at termination. ## Octave function bottles(n) bottle = "bottle"; ofbeer = "of beer"; wall = "on the wall"; for i = n:-1:0 if ( i == 1 ) s = ""; else s = "s"; endif for j = 0:1 w = wall; if ( j == 1 ) w = ""; endif printf("%d %s%s %s %s\n",\ i, bottle, s, ofbeer, w); endfor printf("Take one down, pass it around\n"); endforendfunction bottles(99); ## Oforth "bottles of beer on the wall\n" const: B"bottles of beer\nTake one down, pass it around\n" const: T #[ 100 swap - dup . B print dup . T print 1- . B .cr ] 99 each  ## Ol ## Onyx $Bottles {  dup cvs  bottle' cat exch 1 ne {s' cat} if   of beer' cat} def $GetPronoun { 1 eq {it'}{one'} ifelse cat} def$WriteStanza {  dup dup Bottles  on the wall. ' cat exch Bottles .\n' cat cat  exch Take ' 1 idup GetPronoun  down. Pass it around.\n' cat  exch dec Bottles  on the wall.\n\n' 3 {cat} repeat print flush} def 99 -1 1 {WriteStanza} for

Output:

99 bottles of beer on the wall. 99 bottles of beer.
Take one down. Pass it around.
98 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.
0 bottles of beer on the wall.


## OOC

 sing_line: func (b: Int, suffix: Bool) {  "#{b > 0 ? "#{b}" : "No more"} bottle#{b == 1 ? "" : "s"}" print()  " of beer#{suffix ? " on the wall" : ""}" println()} sing_verse: func (b: Int) {  println()  sing_line(b, true)  sing_line(b, false)  if (b > 0) {    "Take one down, pass it around" println()  } else {    "Go to the store and buy some more" println()    b += 100   }  sing_line(b-1, true)} main: func {  b := 100   while (b > 0) {    sing_verse(--b)  }} 

## ooRexx

The rexx example below runs unchanged on ooRexx

## OpenEdge/Progress

DEFINE VARIABLE amountofbottles AS INTEGER NO-UNDO INITIAL 99.&GLOBAL-DEFINE bbm bottles OF beer&GLOBAL-DEFINE bbs bottle OF beer&GLOBAL-DEFINE otw ON the wall&GLOBAL-DEFINE tow Take one DOWN AND pass it around,&GLOBAL-DEFINE gts Go TO the store AND buy some more,FUNCTION drinkBottle RETURNS INTEGER PRIVATE (INPUT bc AS INTEGER) FORWARD. OUTPUT TO OUTPUT.txt.drinkBottle(amountofbottles).OUTPUT CLOSE. FUNCTION drinkBottle RETURNS INTEGER.    IF bc >= 0 THEN DO:        CASE bc:        WHEN 2 THEN            PUT UNFORMATTED bc " {&bbm} {&otw}, " bc " {&bbm}" SKIP                             "{&tow} " bc - 1 " {&bbs} {&otw}" SKIP.        WHEN 1 THEN            PUT UNFORMATTED bc " {&bbs} {&otw}, " bc " {&bbs}" SKIP                             "{&tow} no more {&bbm} {&otw}" SKIP.        WHEN 0 THEN            PUT UNFORMATTED "no more" " {&bbm} {&otw}, no more {&bbm}" SKIP                             "{&gts} " amountofbottles " {&bbm} {&otw}" SKIP.        OTHERWISE            PUT UNFORMATTED bc " {&bbm} {&otw}, " bc " {&bbm}" SKIP                             "{&tow} " bc - 1 " {&bbm} {&otw}" SKIP.        END CASE.                drinkBottle(bc - 1).        RETURN bc.    END.    RETURN 0. END FUNCTION.

## Order

These examples are taken directly from a much longer tutorial in the Order documentation, which explains the construction of the solution to this problem in great detail.

### "Pure" Order

This solution uses only Order language constructs to generate and manipulate tokens:

#include "order/interpreter.h" ORDER_PP(8let((8B, 8fn(8N,               8cond((8greater(8N, 1),                      8separate(8N, 8quote(bottles)))                     (8equal(8N, 1),                      8quote(1 bottle))                     (8else,                      8quote(no more bottles))))),      8for_each_in_range      (8fn(8N,           8print(8ap(8B, 8N) (of beer on the wall,) 8space                  8ap(8B, 8N) (of beer,) 8space                  (take one down, pass it around,) 8space                  8ap(8B, 8dec(8N)) (of beer on the wall.))),       100, 1)))

### C Preprocessor

...but since most of the logic is simple substitution, it makes more sense (and is significantly more efficient) to make the C Preprocessor do most of the work without the help of the Order interpreter. This version shows how to integrate normal C Preprocessor macros into an Order program:

#include "order/interpreter.h" #define GEN_phrase(N_bottles, N_minus_1_bottles)    \  N_bottles of beer on the wall,                    \  N_bottles of beer, take one down, pass it around, \  N_minus_1_bottles of beer on the wall. #define ORDER_PP_DEF_8bottles                          \ORDER_PP_FN(8fn(8N,                                    \                8cond((8greater(8N, 1),                \                       8separate(8N, 8quote(bottles))) \                      (8equal(8N, 1),                  \                       8quote(1 bottle))               \                      (8else,                          \                       8quote(no more bottles))))) ORDER_PP(8for_each_in_range         (8fn(8N,              8emit(8quote(GEN_phrase),                    8tuple(8bottles(8N),                           8bottles(8dec(8N))))),          100, 1)) #undef GEN_phrase

Either example could obviously also form the core of a C solution (demonstrating the intended use of Order).

## Oxygene

 namespace ConsoleApplication2; interface type  ConsoleApp = class  public    class method Main(args: array of String);  end; implementation method bottles(number: Integer): String;begin    if (number = 1) then         Result := "bottle"    else        Result := "bottles";end; class method ConsoleApp.Main(args: array of String);begin  for n: Integer := 99 downto 1 do  begin      Console.WriteLine("{0} {1} of beer on the wall,",n,bottles(n));      Console.WriteLine("{0} {1} of beer,",n,bottles(n));      Console.WriteLine("Take one down, and pass it around,");      Console.WriteLine("{0} {1} of beer on the wall.",n-1,bottles(n-1));      Console.WriteLine();  end;  Console.ReadKey();end; end. 

## Oz

### Constraint Programming

Note: In real life, you would never solve a simple iterative task like this with constraint programming. This is just for fun.

declare  %% describe the possible solutions of the beer 'puzzle'  proc {BeerDescription Solution}     N = {FD.int 1#99} %% N is an integer in [1, 99]  in    %% distribute starting with highest value    {FD.distribute generic(value:max) [N]}      Solution =     {Bottles N}#" of beer on the wall\n"#     {Bottles N}#" bottles of beer\n"#     "Take one down, pass it around\n"#     {Bottles N-1}#" of beer on the wall\n"  end   %% pluralization  proc {Bottles N Txt}     cond N = 1 then Txt ="1 bottle"     else Txt = N#" bottles"     end  endin  %% show all solutions to the 'puzzle'  {ForAll {SearchAll BeerDescription}   System.showInfo}

### Iterative

declare  fun {Bottles N}     if N == 1 then "1 bottle"     else N#" bottles"     end  endin  for I in 99..1;~1 do     {System.showInfo      {Bottles I}#" of beer on the wall\n"#      {Bottles I}#" bottles of beer\n"#      "Take one down, pass it around\n"#      {Bottles I-1}#" of beer on the wall\n"}  end

## PARI/GP

forstep(n=99,3,-1,  print(n" bottles of beer on the wall");  print(n" bottles of beer");  print("Take one down, pass it around");  print(n-1," bottles of beer on the wall\n"));print("2 bottles of beer on the wall\n2 bottles of beer\nTake one down, pass it around\n1 bottle of beer on the wall\n");print("1 bottle of beer on the wall\n1 bottle of beer\nTake one down, pass it around\nNo more bottles of beer on the wall")

## Perl

#!/usr/bin/perl -w my $verse = <<"VERSE";100 bottles of beer on the wall,100 bottles of beer!Take one down, pass it around!99 bottles of beer on the wall! VERSE {$verse =~ s/(\d+)/$1-1/ge;$verse =~ s/\b1 bottles/1 bottle/g;    my $done =$verse =~ s/\b0 bottle/No bottles/g; # if we make this replacement, we're also done.     print $verse; redo unless$done;}

Alternatively:

for $n (reverse(0..99)){$bottles = sprintf("%s bottle%s of beer on the wall\n",(($n==0)?"No":$n), (($n==1)?"":"s")); print( (($n==99)?"":"$bottles\n") . (($n==0)?"":(substr(${bottles}x2,0,-12) . "\nTake one down, pass it around\n")) );} Correct grammar and nice spacing in modern perl: use 5.10.0;$num = 99;while ($num > 0) { my$s = "s" unless ($num == 1); say "$num bottle$s of beer on the wall,$num bottle$s of beer";$num--;    my $s = "s" unless ($num == 1);     $num = "No more" if ($num == 0);    say "Take one down, pass it around, $num bottle$s of beer on the wall\n"} say "No more bottles of beer on the wall, no more bottles of beer.";say "Go to the store and buy some more, 99 bottles of beer on the wall.";

Using perl5 as a DSL factory leveraging $_'s global nature:  #!/usr/bin/env perluse strict;use warnings; sub bottles() { sprintf qq{%s bottle%s of beer} ,$_ || 'No'               , $_==1 ? '' : 's'; }sub store() {$_=99; qq{Go to the store, buy some more...\n}; }sub wall() { qq{ on the wall\n} }sub take() { $_-- ? qq{Take one down, pass it around\n} : store }do { print bottles, wall , bottles, qq{\n} , take , bottles, qq{\n\n} } for reverse 0..99; ## Phix constant ninetynine = 99 -- (set to 9 for testing) function bottles(integer count) if count=0 then return "no more bottles " elsif count=1 then return "1 bottle " end if if count=-1 then count = ninetynine end if return sprintf("%d bottles ",count) end function function bob(integer count) return bottles(count)&"of beer" end function function up1(string bob) -- Capitalise sentence start (needed just the once, "no more"=>"No more") bob[1] = upper(bob[1]) return bob end function string many = bob(ninetynine) string down = "Take one down, pass it around,\n" for i=ninetynine to 0 by -1 do puts(1,up1(many)&" on the wall,\n") puts(1,many&".\n") if i=0 then down = "Go to the store, buy some more,\n" elsif i=1 then down[6..8] = "it" end if many = bob(i-1) puts(1,down&many&" on the wall.\n\n") end for {} = wait_key()  ## Phixmonti def bottles dup if dup 1 == if "1 bottle" print else dup print " bottles" print endif else "No more bottles" print endifenddef def verse bottles " of beer on the wall" print nl bottles " of beer" print nl "Take one down, pass it around" print nl 1 - bottles " of beer on the wall" print nl nlenddef 99 1 -1 3 tolistfor verse . endfor With syntactic sugar include ..\Utilitys.pmt def bottles dup 0 == if "no more bottles of beer" else dup 1 == if "1 bottle of beer" else dup tostr " bottles of beer" chain endif endifenddef ( 99 1 -1 ) for bottles print " on the wall," ? bottles "," chain ? "take one down, pass it around," ? 1 - bottles print " on the wall." ? nl dropendfor ## PHL Translation of: C module bottles;extern printf; @Integer main [ @Integer 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"); bottles = bottles::dec; printf("%u bottles of beer on the wall\n\n", bottles); } while(bottles > 0); return 0;] ## PHP <?php$plural = 's';foreach (range(99, 1) as $i) { echo "$i bottle$plural of beer on the wall,\n"; echo "$i bottle$plural of beer!\n"; echo "Take one down, pass it around!\n"; if ($i - 1 == 1)        $plural = ''; if ($i > 1)        echo ($i - 1) . " bottle$plural of beer on the wall!\n\n";    else        echo "No more bottles of beer on the wall!\n";}?>

### gettext alternative

supports grammar and translations.

<?php $bottles = 99; while ($bottles > 0) {	printf(ngettext('%d bottle', '%d bottles', $bottles) . " of beer on the wall\n",$bottles);		//X bottles of beer on the wall	printf(ngettext('%d bottle', '%d bottles', $bottles) . " of beer\n",$bottles);				//X bottles of beer	printf("Take one down, pass it around\n");										//Take one down, pass it around 	$bottles--; if ($bottles > 0) {		printf(ngettext('%d bottle', '%d bottles', $bottles) . " of beer on the wall\n\n",$bottles);	//X bottles of beer on the wall	}}printf('No more bottles of beer on the wall');											//No more bottles of beer on the wall

### Using printf

Fun with HEREDOC and printf placeholders

## Pointless

------------------------------------------------------------- Print the lyrics to the song '99 bottles of beer' output =  range(99, 1)  |> map(showBeer)  |> printLines beerFmt = """{} of beer on the wall!{} of beer!You take one down, pass it around{}""" showBeer(n) =  format(    beerFmt,    [showBottle(n), showBottle(n), nextBeer(n - 1)]  ) nextBeer(n) =  if n == 0 then "No more bottles of beer on the wall!"  else format("{} of beer on the wall!\n", [showBottle(n)]) ------------------------------------------------------------- Get appropriate singular / plural form of 'n bottle(s)' showBottle(n) =  format("{} {}", [n, bottleStr])  where bottleStr = if n == 1 then "bottle" else "bottles"

## Pony

### Recursive

actor Main  let _env: Env  new create(env: Env) =>    _env = env    bottles(99)   be bottles(n: U32) =>    if n == 0 then      _env.out.print("No more bottles of beer on the wall, no more bottles of beer.")      _env.out.print("Go to the store and buy some more, 99 bottles of beer on the wall.")    else      if n == 1 then        _env.out.print("1 bottle of beer on the wall, 1 bottle of beer.")        _env.out.print("Take one down and pass it around, no more bottles of beer on the wall.\n")      else        _env.out.print(n.string() + " bottles of beer on the wall, " + n.string() + " bottles of beer.")        _env.out.print("Take one down and pass it around, "+ (n - 1).string() +" bottles of beer on the wall.\n")      end      bottles(n-1)    end

### Iterative

actor Main  let _env: Env  new create(env: Env) =>    _env = env    var n: I32 = 99    repeat      if n == 0 then        _env.out.print("No more bottles of beer on the wall, no more bottles of beer.")        _env.out.print("Go to the store and buy some more, 99 bottles of beer on the wall.")      elseif n == 1 then        _env.out.print("1 bottle of beer on the wall, 1 bottle of beer.")        _env.out.print("Take one down and pass it around, no more bottles of beer on the wall.\n")      else        _env.out.print(n.string() + " bottles of beer on the wall, " + n.string() + " bottles of beer.")        _env.out.print("Take one down and pass it around, "+ (n - 1).string() +" bottles of beer on the wall.\n")      end      n = n - 1    until n < 0 end

## Pop11

define bootles(n);    while n > 0 do        printf(n, '%p bottles of beer on the wall\n');        printf(n, '%p bottles of beer\n');        printf('Take one down, pass it around\n');        n - 1 -> n;        printf(n, '%p bottles of beer on the wall\n');    endwhile;enddefine; bootles(99);

## PostScript

%!PS/Helvetica findfont 9 scalefont setfont /printBeer {    dup    20 string cvs show    ( bottle) show    1 ne    { (s) show } if     ( of beer) show} def /printVerse {    dup    dup    dup    7 mul    50 add     /yPos exch def    15 yPos moveto    printBeer    ( on the wall, ) show    printBeer    (. ) show     (Take one down, pass it around, ) show    1 sub    printBeer    ( on the wall. ) show} def /song {    100 -1 1 { printVerse } for} def songshowpage%%EOF

## Potion

No extra credit.

99 to 1 (i) :   verse = (n) :           (n,     " bottles of beer on the wall\n"            n,     " bottles of beer\n"                   "Take one down, pass it around\n"            n - 1, " bottles of beer on the wall\n")   .    verse(i) join print   "\n" print.

## Processing

Console output

Immediately prints all output to the console.

for (int i = 99; i > 0; i--) {  print(i + " bottles of beer on the wall\n"    + i + " bottles of beer\nTake one down, pass it around\n"    + (i - 1) + " bottles of beer on the wall\n\n");}

Visual and animated

This approach uses Processing's draw loop to display text on the sketch canvas, with a global counter for bottles--draw() is called at the default 60fps, and acts as the for loop. One round of lyrics is displayed at a time, and the counter advances by checking Processing's built-in frameCount. Lyrics may also be advanced manually by clicking the mouse on the canvas.

int i = 99;void setup() {  size(200, 140);}void draw() {  background(0);  text(i + " bottles of beer on the wall\n"     + i + " bottles of beer\nTake one down, pass it around\n" + (i-1) + " bottles of beer on the wall\n\n",     10, 20);  if (frameCount%240==239) next();  // auto-advance every 4 secs}void mouseReleased() {  next();  // manual advance}void next() {  i = max(i-1, 1);  // stop decreasing at 1-0 bottles} 

### Processing Python mode

Translation of: Processing
i = 99def setup():    size(200, 140) def draw():    background(0)    text("{} bottles of beer on the wall\n".format(i) +         "{} bottles of beer\n".format(i) +          "Take one down, pass it around\n" +         "{} bottles of beer on the wall\n\n".format(i - 1),         10, 20)    if frameCount % 240 == 239:  # auto-advance every 4 secs         next() def mouseReleased():    next()  # manual advance def next():    global i    i = max(i - 1, 1)  # stop decreasing at 1-0 bottles

Console output

## Q

bobw:{[n] {x," bottles of beer on the wall\n",x," bottles of beer\nTake one down, pass it around\n",y," bottles of beer on the wall\n\n"} . string (n;n-1)}-1 bobw each reverse 1 + til 99

## QB64

[NOTE]: The code below is an amazing, full-on media event! For a simpler version, click HERE.

## Quackery

   [ stack ]                     is bottles      (         --> [       )   [ join carriage join ]        is addline      (      --> $) [ dup 0 = iff$ 'No more'    else [ dup number$]$ ' bottle' join    swap 1 != if [ char s join ]    $' of beer ' join ] is beers ( n -->$       )   $'on the wall' is wall ( -->$       )   $'Take one down, pass it around' is drink ( -->$       )   $'Go to the store, buy some more' is restock ( -->$       )   [ dup beers wall addline    over beers addline    over 0 = iff      [ nip bottles share        swap restock ]    else drink addline    swap 1 -    beers wall join addline ]   is verse        (       n --> $) [ 1+$ '' swap    dup bottles put    times [ i verse addline ]    bottles release ]           is song         (       n --> $) say 'The song "99 Bottles of Beer on the Wall":' cr cr 99 song echo$ 

## Quill

bottles := void(int count) {  (count > 0) if {    new_count := count - 1;    (      count, " bottles of beer on the wall", nl,      count, " bottles of beer", nl,      "Take one down, pass it around", nl,      new_count, " bottles of beer on the wall"    ) print;    new_count bottles  } else {    "No more bottles of beer on the wall!" print  }};99 bottles

## Quite BASIC

With grammatical support for "1 bottle of beer"

10 let w=" on the wall"20 for n=99 to 1 step -130 let b=" bottles of beer"40 if n=1 then let b=" bottle of beer"50 print n;b;w60 print n;b70 print "Take one down, pass it around"80 if n-1=1 then let b=" bottle of beer"90 if n-1=0 then let b=" bottles of beer"100 print n-1;b;w110 next n

Without grammatical support for "1 bottle of beer"

10 let b=" bottles of beer"20 let w=" on the wall"30 for n=99 to 1 step -140 print n;b;w50 print n;b60 print "Take one down, pass it around"70 print n-1;b;w80 next n

## R

### Simple looping solution

#a naive function to sing for N bottles of beer... song = function(bottles){   for(i in bottles:1){ #for every integer bottles, bottles-1 ... 1     cat(bottles," bottles of beer on the wall \n",bottles," bottles of beer \nTake one down, pass it around \n",        bottles-1, " bottles of beer on the wall \n"," \n" ,sep="")       #join and print the text (\n means new line)         bottles = bottles - 1 #take one down...   } } song(99)#play the song by calling the function

### Vector solutions

#only one line!cat(paste(99:1,ifelse((99:1)!=1," bottles"," bottle")," of beer on the wall\n",99:1,ifelse((99:1)!=1," bottles"," bottle")," of beer\n","Take one down, pass it around\n",98:0,ifelse((98:0)!=1," bottles"," bottle")," of beer on the wall\n\n",sep=""),sep="") #alternativecat(paste(lapply(99:1,function(i){paste(paste(rep(paste(i,' bottle',if(i!=1)'s',' of beer',sep=''),2),collapse =' on the wall\n'),'Take one down, pass it around',paste(i-1,' bottle',if(i!=2)'s',' of beer on the wall',sep=''), sep='\n')}),collapse='\n\n'))

## Ra

 class BottlesOfBeer	**Prints the "99 Bottles of Beer" song"** 	on start 		args := program arguments 		# If no arguments given, print the song once		if args empty			.printSong 		# Otherwise, print the song the given number of times		else			.printSong(integer.parse(args[0])) 	shared 		define printSong(times := 1)			**Print the song the given number of times** 			for times, _printSong 		define _printSong			**Print the song** 			# Print for bottles 99 to 1			for bottle in 99 to 0 by -1 				print "[_bottles(bottle)] of beer on the wall				[_bottles(bottle)] of beer				Take one down, pass it around				[_bottles(bottle - 1)] of beer on the wall				" 			print "No more bottles of beer on the wall			No more bottles of beer			Go to the store, buy some more			99 bottles of beer on the wall" 		define _bottles(bottle as integer) as String			**			If bottle is 0, returns "No more bottles"			If bottle is 1, returns "1 bottle"			Otherwise, returns "[bottle] bottles"			** 			if bottle = 0, return "No more bottles"			if bottle = 1, return "1 bottle"			return "[bottle] bottles" 

## Racket

 #lang racket(define (sing bottles)  (define (plural n) (~a n " bottle" (if (= n 1) "" "s")))  (printf "~a of beer on the wall\n~a of beer\n~           Take one down, pass it around\n~a of beer on the wall\n\n"          (plural bottles) (plural bottles) (plural (sub1 bottles)))  (unless (= 1 bottles) (sing (sub1 bottles))))(sing 99) 

## Raku

(formerly Perl 6)

### A Simple Way

my $b = 99; repeat while --$b {    say "{b $b} on the wall"; say "{b$b}";    say "Take one down, pass it around";    say "{b $b-1} on the wall"; say "";} sub b($b) {    "$b bottle{'s' if$b != 1} of beer";}

### A Clearer Way

Similar to "A Simple Way", but with proper variable and subroutine naming, declarator documentation, strongly-typed function definition, better code reuse, and external ternary logic.

for 99...1 -> $bottles { sing$bottles, :wall;    sing $bottles; say "Take one down, pass it around"; sing$bottles - 1, :wall;    say  "";} #| Prints a verse about a certain number of beers, possibly on a wall.sub sing(    Int $number, #= Number of bottles of beer. Bool :$wall, #= Mention that the beers are on a wall?) {    my $quantity =$number == 0 ?? "No more"      !! $number; my$plural   = $number == 1 ?? "" !! "s"; my$location = $wall ?? " on the wall" !! ""; say "$quantity bottle$plural of beer$location"}

### A More Extravagant Way

Works with: Rakudo version 2015.09
my @quantities = flat (99 ... 1), 'No more', 99;my @bottles = flat 'bottles' xx 98, 'bottle', 'bottles' xx 2;my @actions = flat 'Take one down, pass it around' xx 99,              'Go to the store, buy some more'; for @quantities Z @bottles Z @actions Z    @quantities[1 .. *] Z @bottles[1 .. *]    -> ($a,$b, $c,$d, $e) { say "$a $b of beer on the wall"; say "$a $b of beer"; say$c;    say "$d$e of beer on the wall\n";}

## RapidQ

 dim nBott as integer    nBott = 99 While nBott > 0   Print(str$(nBott ) + " bottle" + iif(nBott=1, "", "s") + " of beer on the wall") Print(str$(nBott ) + " bottle" + iif(nBott=1, "", "s") + " of beer")   Print("Take one down, pass it around")   nBott--   Print(str$(nBott ) + " bottle" + iif(nBott=1, "", "s") + " of beer on the wall" + chr$(10))Wend while inkey$="":wendend  ## Rascal  module demo::basic::Bottles import IO; str bottles(0) = "no more bottles"; str bottles(1) = "1 bottle";default str bottles(int n) = "<n> bottles"; public void sing(){ for(n <- [99 .. 1]){ println("<bottles(n)> of beer on the wall, <bottles(n)> of beer."); println("Take one down, pass it around, <bottles(n-1)> of beer on the wall.\n"); } println("No more bottles of beer on the wall, no more bottles of beer."); println("Go to the store and buy some more, 99 bottles of beer on the wall.");}  ## Raven 99 0 1 range each as$i    $i 1 = if "bottle" as$b    else        "bottles" format as $b$b $i "%d %s of beer on the wall,\n" print$b $i "%d %s of beer,\n" print "Take one down, pass it around,\n" print$i 2 = if        "1 bottle"    else          $i 1 - "%d bottles" format "%s of beer on the wall.\n\n" print Output: Last couple of stanzas are: 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. ## REBOL rebol [ Title: "99 Bottles of Beer" URL: http://rosettacode.org/wiki/99_Bottles_of_Beer] ; The 'bottles' function maintains correct grammar. bottles: func [n /local b][ b: either 1 = n ["bottle"]["bottles"] if 0 = n [n: "no"] reform [n b]] for n 99 1 -1 [print [ bottles n "of beer on the wall" crlf bottles n "of beer" crlf "Take one down, pass it around" crlf bottles n - 1 "of beer on the wall" crlf]] Output (selected highlights): 99 bottles of beer on the wall 2 bottles of beer on the wall 99 bottles of beer 2 bottles of beer Take one down, pass it around Take one down, pass it around 98 bottles of beer on the wall 1 bottle of beer on the wall ...Continues... 1 bottle of beer on the wall 1 bottle of beer Take one down, pass it around no bottles of beer on the wall  This one prints with proper grammar. "Bottles" changed to "bottle" at the end of the 2 line, and throughout the 1 line. 0 changed to "No" in the last line: for i 99 1 -1 [ x: rejoin [ i b: " bottles of beer" o: " on the wall. " i b ". Take one down, pass it around. " (i - 1) b o "^/" ] r: :replace j: "bottles" k: "bottle" switch i [1 [r x j k r at x 10 j k r x "0" "No"] 2 [r at x 40 j k]] print x ] halt Here's a simple 1 line console version: for i 99 1 -1[print rejoin[i b:" bottles of beer"o:" on the wall. "i b". Take one down, pass it around. "(i - 1)b o"^/"]] ## Red Red [ Title: "99 Bottles of Beer" Original-Author: oofoe] ; The 'bottles' function maintains correct grammar. bottles: function [n] [ b: either 1 = n ["bottle"]["bottles"] if 0 = n [n: "no"] form reduce [n b]] repeat x 99 [ n: 100 - x print [ bottles n "of beer on the wall" crlf bottles n "of beer" crlf "Take one down, pass it around" crlf bottles n - 1 "of beer on the wall" crlf ]] ## Relation  program beer(n)if n>1echo n." bottles of beer on the wall"echo n." bottles of beer"elseecho "1 bottle of beer on the wall"echo "1 bottle of beer"end ifecho "Take one down, pass it around"if n > 2echo format(n-1,"%1d")." bottles of beer on the wall"elseecho format(n-1,"%1d")." bottle of beer on the wall"end ifecho " "end program set i = 99while i > 0run beer(i)set i = i-1end while  ## Retro This is based on the Forth example. # 99 Bottles Display the text for the *99 Bottles of Beer* song. ~~~{ 'bottle 'bottles 'of 'beer 'on 'the 'wall 'no 'more 'Take 'one 'down, 'pass 'it 'around } [ dup ':%s_'%s_s:put_sp_; s:format s:evaluate ] a:for-each { [ no more bottles ] [ #1 n:put sp bottle ] [ dup n:put sp bottles ] } 'BOTTLES const :number-bottles dup #2 n:min BOTTLES swap a:fetch call ; :display-verse number-bottles of beer on the wall nl number-bottles of beer nl n:dec Take one down, pass it around nl number-bottles of beer on the wall nl ; :verses (n-) repeat 0; nl display-verse again ; #99 verses ~~~ ## REXX Complete with a PSA (Public Service Announcement) comment. /*REXX program displays lyrics to the infamous song "99 Bottles of Beer on the Wall". */parse arg N .; if N=='' | N=="," then N=99 /*allow number of bottles be specified.*/ /* [↓] downward count of beer bottles.*/ do #=N by -1 for N /*start the countdown and singdown. */ say # 'bottle's(#) "of beer on the wall," /*sing the number bottles of beer. */ say # 'bottle's(#) "of beer." /* ··· and also the song's refrain.*/ say 'Take one down, pass it around,' /*take a beer bottle ─── and share it.*/ m= # - 1 /*M: the number of bottles we have now*/ if m==0 then m= 'no' /*use word "no" instead of numeric 0.*/ say m 'bottle's(m) "of beer on the wall." /*sing the beer bottle inventory. */ say /*show a blank line between the verses.*/ end /*#*/ /*PSA: Please drink responsibly. */ /*Not quite tanked? Then sing it. */say 'No more bottles of beer on the wall,' /*Finally! The last verse. */say 'no more bottles of beer.' /*this is sooooooo sad and forlorn ··· */say 'Go to the store and buy some more,' /*obtain replenishment of the beer. */say N 'bottles of beer on the wall.' /*all is well in the ole town tavern. */exit /*we're all done, and also sloshed !. *//*──────────────────────────────────────────────────────────────────────────────────────*/s: if arg(1)=1 then return ''; return 's' /*simple pluralizer for gooder English.*/ output Below is the first and last three verses of the song: 99 bottles of beer on the wall, 99 bottles of beer. Take one down, pass it around, 98 bottles of beer on the wall. 98 bottles of beer on the wall, 98 bottles of beer. Take one down, pass it around, 97 bottles of beer on the wall. 97 bottles of beer on the wall, 97 bottles of beer. Take one down, pass it around, 96 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, no 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.  ## Ring This is a simple solution for i = 99 to 0 step -1switch ion 0see "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."on 1see "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. "othersee string(i) + " bottles of beer on the wall, " + string(i) + " bottles of beer.Take one down and pass it around, " + string(i-1) + " bottles of beer on the wall. "offnext Output: 99 bottles of beer on the wall, 99 bottles of beer. Take one down, pass it around, 98 bottles of beer on the wall. ∙ ∙ ∙ 1 bottle of beer on the wall, 1 bottle of beer. Take one down, pass it around, no 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.  ## Rockstar Rockstar solution without special cases for the last 2 verses. Love is " bottles of beer on the wall"Problems are " bottles of beer"Carol says Take one down, pass it aroundThe beers were numbering fa'too'manyWhile the beers ain't nothingShout it with LoveShout it with ProblemsSay Carol,Knock the beers downSay it with Love  ## RPG Works with: RPGIII  H/TITLE 99 Bottles of Beer on the Wall - RPGIII (IBM System/38) F******************************************************************** F* F* Lines with an asterisk in column 7 (such as this one) are comments. F* F* The character in column 6 specifies the form type. Before the first F* use of each form type is a comment with the template for the form. F* F******************************************************************** F* File Description Specifications F* F* Specify a default printer file for output, program described, F* 132 columns wide, and an overflow indicator OV. The overflow F* indicator is turned on when data is output to the last usable F* line (line 60, for the default printer file QSYSPRT). F* F*ilenameIPEAF....RlenLK1AIOvKlocEDevice+......KExit++Entry+A....U1 FQSYSPRT O F 132 OV PRINTER F* C******************************************************************** C* If there were an input file, the RPG cycle would automatically C* execute the output lines; since there is no input file, output C* lines are produced as "exception" output with the EXCPT opcode. C* C* Calculation Specifications C* vvvvvvvvv-- conditionally executes lines if indicators are on/off C*0N01N02N03Factor1+++OpcdeFactor2+++ResultLenDHHiLoEqComments+++++++ C* C* Zero, then add 99 to a variable named #BOTLS, which is defined C* as packed decimal, 3 positions, 0 decimal places. C Z-ADD99 #BOTLS 30 C* C* Do until #BOTLS = 0. Each loop produces one complete verse. C #BOTLS DOUEQ0 C* C* When the overflow indicator is turned on, start a new page. C* The indicator is automatically turned on when the overflow C* line is printed on, and it is automatically turned off C* when the heading is printed. C OV EXCPTNEWPAG C* C* Print exception lines with names "LYRIC1" and "LYRIC2". C EXCPTLYRIC1 C EXCPTLYRIC2 C* C* Subtract 1 from #BOTLS, and turn on indicator LR (Last Record) C* if the result is equal to zero (Eq); if LR is on, the program C* will terminate at the end of the current cycle. C SUB 1 #BOTLS LR C* C* Compare #BOTLS to 1, and turn on indicator 01 if equal. C #BOTLS COMP 1 01 C* C* Print exception lines with name "LYRIC1". C EXCPTLYRIC1 C* C* If LR is not on, print exception lines with name "SKIPLN" C* (which, in this case, will produce a blank line between verses). C NLR EXCPTSKIPLN C* C END end do C* O******************************************************************** O* Output Specifications O* .-- E means "Exception" ("H" Header, "D" Detail, "T" Total) O* v vv-- before printing, skip to line # 1 (of the next page) O*ame++++DFBASbSaN01N02N03Excnam........................................... OQSYSPRT E 1 NEWPAG O* v-- space 1 line after printing O E 1 LYRIC1 O* O* .........-- conditionally print lines if indicators on/off O* vvvvvvvvv v-- edit code Z (suppress leading Zeroes) O*...............N01N02N03Field+YBEnd+PConstant/editword+++++++++ O #BOTLSZ 3 O N01NLR 11 'bottles' O N01NLR 31 'of beer on the wall' O 01NLR 10 'bottle' O 01NLR 30 'of beer on the wall' O LR 16 'No more bottles' O LR 36 'of beer on the wall' O E 1 LYRIC2 O #BOTLSZ 3 O N01 19 'bottles of beer' O 01 18 'bottle of beer' O E 1 LYRIC2 O 14 'Take one down' O E 1 LYRIC2 O 15 'Pass it around' O E 1 SKIPLN  ## RPL/2 ### Simple solution BEER<< 99 do dup ->str PLURAL " on the wall," + disp dup ->str PLURAL "." + disp "Take one down, pass it around," disp 1 - if dup then dup ->str else "No more" end PLURAL " on the wall." + disp "" disp until dup 0 == end drop>> PLURAL<< " bottle" + over if 1 <> then "s" + end " of beer" +>> ### Recursive and multithreaded solution BOTTLES<< // Child process is started. 100 'RECURSIVE' detach -> PROC << do PROC recv until end drop2 do // Parent waits for datas sent by child. do PROC recv until end list-> drop dup " on the wall," + disp "." + disp "Take one down, pass it around," disp if dup 1 same not then do PROC recv until end list-> drop else 1 "No more bottles of beer" end " on the wall." + disp drop "" disp until 1 same end // Parent waits for Child's death. PROC wfproc >>>> RECURSIVE<< while dup repeat 1 - dup dup ->str if over 1 > then " bottles " else " bottle " end + "of beer" + 2 ->list dup // Child send datas to parent process. send send // Recursive function is caught. RECURSIVE end>> ## Ruby plural = 's'99.downto(1) do |i| puts "#{i} bottle#{plural} of beer on the wall," puts "#{i} bottle#{plural} of beer" puts "Take one down, pass it around!" plural = '' if i - 1 == 1 if i > 1 puts "#{i-1} bottle#{plural} of beer on the wall!" puts else puts "No more bottles of beer on the wall!" endend Ruby has variable traces, so we can do trace_var :$bottle_num do |val|  $bottles = %Q{#{val == 0 ? 'No more' : val.to_s} bottle#{val == 1 ? '' : 's'}}end ($bottle_num = 99).times do  puts "#{$bottles} of beer on the wall" puts "#{$bottles} of beer"  puts "Take one down, pass it around"  $bottle_num -= 1 puts "#{$bottles} of beer on the wall"  puts ""end

or...

def bottles`