game21<-function(first = c("player","ai","random"),sleep=.5){
  state = 0
  finished = F
  turn = 1
  if(length(first)==1 && startsWith(tolower(first),"r")){
    first = rbinom(1,1,.5)
  }else{
    first = (length(first)>1 || startsWith(tolower(first),"p"))
  }
  while(!finished){
    if(turn>1 || first){
      cat("The total is now",state,"\n");Sys.sleep(sleep)
      while(T){
        player.move = readline(prompt = "Enter move: ")
        if((player.move=="1"||player.move=="2"||player.move=="3") && state+as.numeric(player.move)<=21){
          player.move = as.numeric(player.move)
          state = state + player.move
          break
        }else if(tolower(player.move)=="exit"|tolower(player.move)=="quit"|tolower(player.move)=="end"){
          cat("Goodbye.\n")
          finished = T
          break
        }else{
          cat("Error: invaid entry.\n")
        }
      }
    }
    if(state == 21){
      cat("You win!\n")
      finished = T
    }
    if(!finished){
      cat("The total is now",state,"\n");Sys.sleep(sleep)
      while(T){
        ai.move = sample(1:3,1)
        if(state+ai.move<=21){
          break
        }
      }
      state = state + ai.move
      cat("The AI chooses",ai.move,"\n");Sys.sleep(sleep)
      if(state == 21){
        cat("The AI wins!\n")
        finished = T
      }
    }
    turn = turn + 1
  }
}


#lang racket

(define limit 21)
(define max-resp 3)

(define (get-resp)
  (let loop ()
    (match (read-line)
      [(app (conjoin string? string->number) n)
       #:when (and (exact-integer? n) (<= 1 n max-resp))
       n]
      ["q" (exit)]
      [n (printf "~a is not in range 1 and ~a\n" n max-resp)
         (loop)])))

(define (win human?) (printf "~a wins\n" (if human? "Human" "Computer")))

(printf "The ~a game. Each player chooses to add a number
in range 1 and ~a to a running total.
The player whose turn it is when the total reaches exactly ~a wins.
Enter q to quit.\n\n" limit max-resp limit)

(let loop ([total 0] [human-turn? (= 0 (random 2))])
  (define new-total
    (+ total
       (cond
         [human-turn? (printf "Running total is: ~a\n" total)
                      (printf "Your turn:\n")
                      (get-resp)]
         [else (define resp (random 1 (add1 max-resp)))
               (printf "Computer plays: ~a\n" resp)
               resp])))
  (cond
    [(= new-total limit) (win human-turn?)]
    [(> new-total limit) (win (not human-turn?))]
    [else (loop new-total (not human-turn?))]))


say qq :to 'HERE';
    The 21 game. Each player chooses to add 1, 2, or 3 to a running total.
    The player whose turn it is when the total reaches 21 wins. Enter q to quit.
    HERE

my $total = 0;
loop {
    say "Running total is: $total";
    my ($me,$comp);
    loop {
        $me = prompt 'What number do you play> ';
        last if $me ~~ /^<[123]>$/;
        insult $me;
    }
    $total += $me;
    win('Human') if $total >= 21;
    say "Computer plays: { $comp = (1,2,3).roll }\n";
    $total += $comp;
    win('Computer') if $total >= 21;
}

sub win ($player) {
    say "$player wins.";
    exit;
}

sub insult ($g) {
    exit if $g eq 'q';
    print ('Yo mama,', 'Jeez,', 'Ummmm,', 'Grow up,', 'Did you even READ the instructions?').roll;
    say " $g is not an integer between 1 & 3..."
}


/*REXX program plays the  21  game with a human,  each player chooses 1, 2, or 3  which */
/*──────────── is added to the current sum, the first player to reach  21  exactly wins.*/
sep= copies('─', 8);  sep2= " "copies('═', 8)" " /*construct an eye─catching msg fences.*/
say sep  'Playing the  21  game.'                /*tell what's happening here at the zoo*/
$=0;                       goal= 21              /*the sum [or running total]  (so far).*/
    do j=1  while $<goal;  call g                /*obtain the user's number via a prompt*/
    if x\==0    then call tot x, 1               /*Not 0?   The user wants to go first. */
    if $==goal  then leave                       /*the user won the game with the last #*/
    call ?;     if y==.  then y= random(1, 3)    /*get computer's choice  or  a random #*/
    say sep 'The computer chooses '     y     " as its choice."         /*inform player.*/
    call tot y, 0                                /*call subroutine to show the total.   */
    end   /*j*/
say
if who  then say sep  'Congratulations!   You have won the  21  game.'
        else say sep  'The computer has won the  21  game.'
exit 0                                           /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
?:   y=.;   do c=1  for 3  until y\==.;  if (c+$) // 4 == 1  then y= c;    end;     return
ser: if bad  then return;  bad=1;  say;  say;  say sep '***error***' arg(1);  say;  return
tot: arg q,who; $=$+q; say sep 'The game total is now' sep2 $ sep2; /*add; show $*/ return
/*──────────────────────────────────────────────────────────────────────────────────────*/
g: low = (j \== 1)                               /*allow user to have computer go first.*/
     do until \bad;   bad= 0;     say            /*prompt 'til user gives a good number.*/
     say sep  'Please enter a number from ' low " ───► 3               (or Quit):"
     if j=1  then say sep '[A value of 0 (zero) means you want the computer to go first.]'
     parse pull x _ . 1 ox;   upper x            /*obtain user's lowercase response(s). */
     if   x=''             then call ser "Nothing entered."
     if _\==''             then call ser "Too many arguments entered: "       ox
     if abbrev('QUIT', x, 1)  then do;   say;      say sep  "quitting.";      exit 1;  end
     if \datatype(x, 'N')  then call ser "Argument isn't numeric: "           ox
     if \datatype(x, 'W')  then call ser "Number isn't an integer: "          ox
     if x<0                then call ser "Number can't be negative: "          x
     if x=0  &  j>1        then call ser "Number can't be zero: "              x
     if x>3                then call ser "Number is too large  (>3): "         x
     if bad                then iterate          /*Had an error? Then get another number*/
     x= x/1; if $+x>goal   then call ser "Number will cause the sum to exceed " goal': ' x
     end   /*until*/;           return


# Project : 21 Game

load "guilib.ring"

limit = 21
posold = 0
button = list(limit)
mynum = list(3)
yournum = list(3)

new qapp
        {
        win1 = new qwidget() {
                  setwindowtitle("21 Game")
                  setgeometry(100,100,1000,600)
                  label1 = new qlabel(win1) {
                              setgeometry(10,10,1000,600)
                              settext("")
                  }

                  label2 = new qlabel(win1) {
                              setgeometry(240,50,120,40)
                              setAlignment(Qt_AlignHCenter)
                              setFont(new qFont("Verdana",12,100,0))
                              settext("my number:")
                  }

                  label3 = new qlabel(win1) {
                              setgeometry(640,50,120,40)
                              setAlignment(Qt_AlignHCenter)
                              setFont(new qFont("Verdana",12,100,0))
                              settext("your number:")
                  }

                  for p = 1 to 3
                       mynum[p] = new qpushbutton(win1) {
                                          setgeometry(200+p*40,100,40,40)
                                          setstylesheet("background-color:orange")
                                          settext(string(p))
                                          setclickevent("choose(" + string(p) + ",1)")
                                          }
                   next

                   for p = 1 to 3
                        yournum[p] = new qpushbutton(win1) {
                                             setgeometry(600+p*40,100,40,40)
                                             setstylesheet("background-color:white")
                                             settext(string(p))
                                             setclickevent("choose(" + string(p) + ",2)")
                                             }
                   next

                   for n = 1 to limit
                        button[n] = new qpushbutton(win1) {
                                          setgeometry(40+n*40,190,40,40)
                                          settext(string(n))
                                          }
                    next
                    show()
        }
        exec()
        }

func choose(ch,ym)
        pos = posold + ch
        if pos > limit
           msg = "You must choose number from 1 to " + string(limit - posold)
           msgBox(msg)
           for n = 1 to 3
                mynum[n].setenabled(false)
                yournum[n].setenabled(false)
           next
           return
        ok
        for n = posold+1 to pos
             if ym = 1
                button[n] { setstylesheet("background-color:orange") }
             else
                button[n] { setstylesheet("background-color:white") }
             ok
        next
        posold = pos
        if ym = 1
           for n = 1 to 3
                mynum[n].setenabled(false)
                yournum[n].setenabled(true)
           next
         else
           for n = 1 to 3
                mynum[n].setenabled(true)
                yournum[n].setenabled(false)
           next
         ok
         if pos = 21
            if ym = 1
               msgBox("I won!")
            else
               msgBox("You won!")
            ok
         ok

func msgBox(text) {
	m = new qMessageBox(win1) {
	       setWindowTitle("21 Game")
	       setText(text)
	       show()
	       }
        }


# 21 Game - an example in Ruby for Rosetta Code.

GOAL = 21
MIN_MOVE = 1
MAX_MOVE = 3

DESCRIPTION = "
*** Welcome to the 21 Game! ***
21 is a two player game.
Each player chooses to add 1, 2 or 3 to a running total.
The player whose turn it is when the total reaches 21 will win the game.
The running total starts at zero.

The players start the game in turn.
Enter q to quit at any time.
"

#
# Returns the best move to play.
#
def best_move(total)
  move = rand(1..3)
  MIN_MOVE.upto(MAX_MOVE) do |i|
    move = i if (total + i - 1) % (MAX_MOVE + 1) == 0
  end
  MIN_MOVE.upto(MAX_MOVE) do |i|
    move = i if total + i == GOAL
  end
  move
end

#
# Gets the move of the player.
#
def get_move
  print "Your choice between #{MIN_MOVE} and #{MAX_MOVE}: "
  answer = gets
  move = answer.to_i
  until move.between?(MIN_MOVE, MAX_MOVE)
    exit if answer.chomp == 'q'
    print 'Invalid choice. Try again: '
    answer = gets
    move = answer.to_i
  end
  move
end

#
# Asks the player to restart a game and returns the answer.
#
def restart?
  print 'Do you want to restart (y/n)? '
  restart = gets.chomp
  until ['y', 'n'].include?(restart)
    print 'Your answer is not a valid choice. Try again: '
    restart = gets.chomp
  end
  restart == 'y'
end

#
# Run a game. The +player+ argument is the player that starts:
# * 1 for human
# * 0 for computer
#
def game(player)
  total = round = 0
  while total < GOAL
    round += 1
    puts "--- ROUND #{round} ---\n\n"
    player = (player + 1) % 2
    if player == 0
      move = best_move(total)
      puts "The computer chooses #{move}."
    else
      move = get_move
    end
    total += move
    puts "Running total is now #{total}.\n\n"
  end
  if player == 0
    puts 'Sorry, the computer has won!'
    return false
  end
  puts 'Well done, you have won!'
  true
end

# MAIN
puts DESCRIPTION
run = true
computer_wins = human_wins = 0
games_counter = player = 1
while run
  puts "\n=== START GAME #{games_counter} ==="
  player = (player + 1) % 2
  if game(player)
    human_wins += 1
  else
    computer_wins += 1
  end
  puts "\nComputer wins #{computer_wins} games, you wins #{human_wins} game."
  games_counter += 1
  run = restart?
end
puts 'Good bye!'


use rand::Rng;
use std::io;

#[derive(Clone)]
enum PlayerType {
    Human,
    Computer,
}

#[derive(Clone)]
struct Player {
    name: String,
    wins: u32,  // holds wins
    level: u32, // difficulty level of Computer
    player_type: PlayerType,
}

trait Choose {
    fn choose(&self, game: &Game) -> u8;
}

impl Player {
    fn new(name: &str, player_type: PlayerType, level: u32) -> Player {
        Player {
            name: String::from(name),
            wins: 0,
            level,
            player_type,
        }
    }
    fn get_name(&self) -> &str {
        &self.name[..]
    }
    fn get_level(&self) -> u32 {
        self.level
    }
    fn add_win(&mut self) {
        self.wins += 1
    }
    fn level_up(&mut self) {
        self.level += 1
    }
}

impl Choose for Player {
    fn choose(&self, game: &Game) -> u8 {
        match self.player_type {
            PlayerType::Human => loop {
                let max_choice = game.max_choice();
                match max_choice {
                    1 => println!("Enter a number 1 to win (or quit):"),
                    _ => println!("Enter a number between 1 and {} (or quit):", max_choice)
                }
                let mut guess = String::new();
                io::stdin()
                    .read_line(&mut guess)
                    .expect("Failed to read line");
                if guess.trim() == "quit" {
                    return 0
                }
                let guess: u8 = match guess.trim().parse() {
                    Ok(num) if num >= 1 && num <= max_choice => num,
                    Ok(_) => continue,
                    Err(_) => continue,
                };
                return guess;
            },
            PlayerType::Computer => match self.level {
                5 => match game.get_total() {
                    total if total == 20 => 1,
                    total if total == 19 => 2,
                    total if total == 18 => 3,
                    _ => 1,
                },
                4 => match game.get_total() {
                    total if total == 20 => 1,
                    total if total == 19 => 2,
                    total if total == 18 => 3,
                    _ => rand::thread_rng().gen_range(1, 3),
                },
                3 => match game.get_total() {
                    total if total == 20 => 1,
                    total if total == 19 => 2,
                    total if total == 18 => 3,
                    _ => rand::thread_rng().gen_range(1, 4),
                },
                2 => match game.get_total() {
                    total if total == 20 => 1,
                    total if total == 19 => 2,
                    _ => rand::thread_rng().gen_range(1, 3),
                },
                1 => 1,
                _ => match game.get_total() {
                    total if total == 20 => 1,
                    total if total == 19 => 2,
                    total if total == 18 => 3,
                    _ => match game.get_remaining() % 4 {
                        0 => rand::thread_rng().gen_range(1, 4),
                        _ => game.get_remaining() % 4,
                    },
                },
            },
        }
    }
}

struct Game {
    players: Vec<Player>,
    turn: u8,
    total: u8,
    start: u8, // determines which player goes first
}

impl Game {
    fn init(players: &Vec<Player>) -> Game {
        Game {
            players: players.to_vec(),
            turn: 1,
            total: 0,
            start: rand::thread_rng().gen_range(0, 2),
        }
    }
    fn play(&mut self) -> &Player {
        loop {
            println!(
                "Total now {} (remaining: {})",
                self.get_total(),
                self.get_remaining()
            );
            {
                let player = self.whose_turn();
                println!("Turn: {} ({} turn)", self.get_turn(), player.get_name());
                let choice = player.choose(&self);
                if choice == 0 {
                    self.next_turn();
                    break; // quit
                }
                println!("{} choose {}", player.get_name(), choice);
                self.add_total(choice)
            }
            if self.get_total() >= 21 {
                break;
            }
            println!("");
            self.next_turn();
        }
        self.whose_turn()
    }
    fn add_total(&mut self, choice: u8) {
        self.total += choice;
    }
    fn next_turn(&mut self) {
        self.turn += 1;
    }
    fn whose_turn(&self) -> &Player {
        let index: usize = ((self.turn + self.start) % 2).into();
        &self.players[index]
    }
    fn get_total(&self) -> u8 {
        self.total
    }
    fn get_remaining(&self) -> u8 {
        21 - self.total
    }
    fn max_choice(&self) -> u8 {
        match self.get_remaining() {
            1 => 1,
            2 => 2,
            _ => 3
        }
    }
    fn get_turn(&self) -> u8 {
        self.turn
    }
}

fn main() {
    let mut game_count = 0;
    let mut players = vec![
        Player::new("human", PlayerType::Human, 0),
        Player::new("computer", PlayerType::Computer, 1),
    ];
    println!("21 Game");
    println!("Press enter key to start");
    {
        let _ = io::stdin().read_line(&mut String::new());
    }
    loop {
        game_count += 1;
        let mut game = Game::init(&players);
        let winner = game.play();
        {
            let mut index = 0;
            while index < players.len() {
                if players[index].get_name() == winner.get_name() {
                    players[index].add_win();
                }
                index += 1
            }
        }
        println!("\n{} won game {}\n", winner.get_name(), game_count);
        // limit game count
        if game_count >= 10000 {
            break;
        }
        // ask player if they want to keep on playing
        println!("Press enter key to play again (or quit):");
        let mut reply = String::new();
        io::stdin()
            .read_line(&mut reply)
            .expect("Failed to read line");
        if reply.trim() == "quit" {
            break;
        }
        // level up computer
        if winner.get_name() != "computer" {
            println!("Computer leveling up ...");
            players[1].level_up();
            println!("Computer now level {}!", players[1].get_level());
            println!("Beware!\n");
        }
    }
    println!("player: {} win: {}", players[0].get_name(), players[0].wins);
    println!("player: {} win: {}", players[1].get_name(), players[1].wins);
}


object Game21 {

  import scala.collection.mutable.ListBuffer
  import scala.util.Random

  val N = 21 // the same game would also work for N other than 21...

  val RND = new Random() // singular random number generator; add a seed number, if you want reproducibility

  /** tuple: name and a play function: (rest: remaining number, last: value of opponent's last move) => new move
    */
  type Player = (String, (Int,Int) => Int)

  // indeed, the following could also be written using a class and instances, I've choosen a
  // more functional and math way (using tuples)...
  val playerRandom:Player = ("RandomRobot", { (rest, last) =>
    if (rest <= 3) rest
    else 1 + RND.nextInt(3)
  })
  val playerBest:Player = ("BestRobot", { (rest, last) =>
    val i = rest % 4
    if (i > 0) i else 1 + RND.nextInt(3)
  })
  val playerHuman:Player = ("YOU", { (rest, last) =>
    println("Rest: "+rest)
    println("Last: "+last)
    var in = ""
    while (in!="1" && in!="2" && in!="3") {
      in = scala.io.StdIn.readLine("Your move (1,2,3,q)> ").trim
      if ("q" == in)
        throw new Exception("q => quit")
    }
    in.toInt
  })

  /** Execute a whole game. NOTE that we're counting DOWN from N to 0!
    * @param players
    * @return list of all moves
    */
  def play(players:Seq[Player]):Seq[Int] = {
    require(players.size == 2)
    var last = -1
    var rest = N
    var p = 0 // player 0 always starts
    val l = ListBuffer[Int]() // list of all moves
    while (rest > 0) {
      last = players(p)._2(rest,last)
      require(1<=last && last<=3,"Player must always play 1,2,3: "+last)
      l += last
      rest -= last
      p = 1 - p // other player's turn
    }
    l.toSeq
  }

  /** Evaluate a whole game.
    * @param game list of moves of one game
    * @param rest mainly for recursion
    * @return evaluation, for each move a tuple: (rest, what was played, whether this player won in the end)
    */
  def evaluate(game:Seq[Int],rest:Int=N):Seq[(Int,Int,Boolean)] = {
    if (game.size == 0) Seq()
    else Seq((rest,game.head,game.size%2 == 1)) ++ evaluate(game.tail,rest - game.head)
  }

  def main(args: Array[String]): Unit = {
    // here you can put whatever player combination you like
    val players = Seq(playerRandom,playerRandom) // random robot vs random robot
    //val players = Seq(playerRandom,playerBest) // random robot vs best robot
    //val players = Seq(playerHuman,playerBest) // You vs best robot
    var p0won = 0
    val n = 1000 // number of games to play
    var m = 0 // games actually played (a human player might quit before n)
    try {
      (1 to n).foreach { i =>
        val g = play(players)
        require(g.sum == N) // some validity checks
        val e = evaluate(g)
        require(e.size == g.size && e.last._3 && e(0)._3 != e(1)._3) // some validity checks
        if (e(0)._3) p0won += 1
        m += 1
        println(i + ": " + players(0)._1 + " " + (if (e(0)._3) "won" else "lost") + " against " + players(1)._1 + ". " + g + " => " + e)
      }
    } catch {
      case t:Throwable => println(t.getMessage)
    }
    println("Player0: "+players(0)._1)
    println("Player1: "+players(1)._1)
    println(f"Player0 won ${p0won} times out of ${m}, or ${p0won * 100.0 / m}%%")
  }
}


' Game 21 in VB.NET - an example for Rosetta Code

Class MainWindow
    Private Const GOAL As Integer = 21
    Private total As Integer = 0
    Private random As New Random

    Private Sub Update(box As TextBox, player As String, move As Integer)
        total = total + move
        box.Text = move
        boxTotal.Text = total
        If total + 1 > GOAL Then button1.IsEnabled = False
        If total + 2 > GOAL Then button2.IsEnabled = False
        If total + 3 > GOAL Then button3.IsEnabled = False
        If total = GOAL Then
            winner.Content = $"The winner is {player}."
        End If
    End Sub

    Private Sub Ai()
        Dim move As Integer = 1
        For i = 1 To 3
            If (total + i - 1) Mod 4 = 0 Then move = i
        Next i
        For i = 1 To 3
            If total + i = GOAL Then move = i
        Next i
        Update(boxAI, "AI", move)
    End Sub

    Private Sub Choice(sender As Object, e As RoutedEventArgs) _
            Handles button1.Click, button2.Click, button3.Click
        Update(boxHuman, "human", sender.Content)
        If total < GOAL Then Ai()
    End Sub

    ' StartGame method handles both OnLoad (WM_INIT?) event
    ' as well as the restart of the game after user press the 'restart' button.
    '
    Private Sub StartGame(sender As Object, e As RoutedEventArgs) Handles restart.Click

        total = 0

        boxAI.Text = ""
        boxHuman.Text = ""
        boxTotal.Text = ""
        'first.Content = "" ' It is not necessary, see below.
        winner.Content = ""

        button1.IsEnabled = True
        button2.IsEnabled = True
        button3.IsEnabled = True

        ' The random.Next(2) return pseudorandomly either 0 or 1. Generally
        ' random.Next(n) Return a value from 0 (inclusive) To n - 1 (inclusive).
        '
        If random.Next(2) = 0 Then
            first.Content = "First player is AI player."
            Ai()
        Else
            first.Content = "First player is human player."
        End If
    End Sub
End Class


import os
import rand
import rand.seed
import strconv

fn get_choice(mut total &int) bool {
    for {
        text := os.input("Your choice 1 to 3 : ")
        if text == "q" || text == "Q" {
            return true
        }
        input := strconv.atoi(text) or {-1}
        if input == -1 {
            println("Invalid number, try again")
            continue
        }
        new_total := *total + input
        match true {
            input < 1 || input > 3 {
                println("Out of range, try again")
            }
            new_total > 21 {
                println("Too big, try again")
            }
            else {
                total = new_total
                println("Running total is now ${*total}")
                return false
            }
        }
    }
    return false
}

fn main() {
    rand.seed(seed.time_seed_array(2))
    mut computer := rand.intn(2) or {0} != 0
    println("Enter q to quit at any time\n")
    if computer {
        println("The computer will choose first")
    } else {
        println("You will choose first")
    }
    println("\nRunning total is now 0\n")
    mut choice := 0
    mut total := 0
    for round := 1; ; round++ {
        println("ROUND $round:\n")
        for i := 0; i < 2; i++ {
            if computer {
                if total < 18 {
                    choice = 1 + rand.intn(3) or {1}
                } else {
                    choice = 21 - total
                }
                total += choice
                println("The computer chooses $choice")
                println("Running total is now $total")
                if total == 21 {
                    println("\nSo, commiserations, the computer has won!")
                    return
                }
            } else {
                quit := get_choice(mut total)
                if quit {
                    println("OK, quitting the game")
                    return
                }
                if total == 21 {
                    println("\nSo, congratulations, you've won!")
                    return
                }
            }
            println('')
            computer = !computer
        }
    }
}


import "/fmt" for Conv
import "/ioutil" for Input
import "random" for Random

var total = 0
var quit = false

var getChoice = Fn.new {
    while (true) {
        var input = Input.integer("Your choice 1 to 3: ", 0, 3)
        if (input == 0) {
            quit = true
            return
        }
        var newTotal = total + input
        if (newTotal > 21) {
            System.print("Too big, try again")
        } else {
            total = newTotal
            System.print("Running total is now %(total)")
            return
        }
    }
}

var rand = Random.new()
var computer = Conv.itob(rand.int(2))
System.print("Enter 0 to quit at any time\n")
if (computer) {
    System.print("The computer will choose first")
} else {
    System.print("You will choose first")
}
System.print("\nRunning total is now 0\n")
var round = 1
while (true) {
    System.print("ROUND %(round):\n")
    for (i in 0..1) {
        if (computer) {
            var choice = (total < 18) ? 1 + rand.int(3) : 21 - total
            total = total + choice
            System.print("The computer chooses %(choice)")
            System.print("Running total is now %(total)")
            if (total == 21) {
                System.print("\nSo, commiserations, the computer has won!")
                return
            }
        } else {
            getChoice.call()
            if (quit) {
                System.print("OK, quitting the game")
                return
            }
            if (total == 21) {
                System.print("\nSo, congratulations, you've won!")
                return
            }
        }
        System.print()
        computer = !computer
    }
    round = round + 1
}


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


\ 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


/* 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              */
/*********************************/
.data
szMessLine1:        .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            */
/*********************************/
.bss
sZoneConv:        .skip 24
/*********************************/
/*  code section                 */
/*********************************/
.text
.global main
main:                            // entry of program
    mov x2,#MAXI
1:
    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 affichageMess
2:
    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 szCarriageReturn
qAdrszMessLine1:          .quad szMessLine1
qAdrszMessLine2:          .quad szMessLine2
qAdrszMessLine3:          .quad szMessLine3
qAdrszMessLine4:          .quad szMessLine4
qAdrsZoneConv:            .quad sZoneConv

/********************************************************/
/*        File Include fonctions                        */
/********************************************************/
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"


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.


PROC Bottles(BYTE i)
  IF i=0 THEN
    Print("No more")
  ELSE
    PrintB(i)
  FI
  Print(" bottle")
  IF i#1 THEN
    Print("s")
  FI
RETURN

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
  OD
RETURN


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


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;


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


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


begin
  integer n;

  for n:= 99 step -1 until 2 do
     begin
      outinteger(1,n);
	  outstring(1,"bottles of beer on the wall,");
      outinteger(1,n);
      outstring(1,"bottles of beer.\nTake one down and pass it around,");
      outstring(1,"of beer on the wall...\n\n")
     end;

  outstring(1," 1 bottle of beer on the wall, 1 bottle of beer.\n");
  outstring(1,"Take one down and pass it around, no more bottles of beer on the wall...\n\n");

  outstring(1,"No more bottles of beer on the wall, no more bottles of beer.\n");
  outstring(1,"Go to the store and buy some more, 99 bottles of beer on the wall.")
end


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
)


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


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


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


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


     bob  ←  { (⍕⍵), ' bottle', (1=⍵)↓'s of beer'}
     bobw ←  {(bob ⍵) , ' on the wall'}
     beer ←  { (bobw ⍵) , ', ', (bob ⍵) , '; take one down and pass it around, ', bobw ⍵-1}


repeat with beerCount from 99 to 1 by -1
  set bottles to "bottles"
  if beerCount < 99 then
    if beerCount = 1 then
      set bottles to "bottle"
    end
    log "" & beerCount & " " & bottles & " of beer on the wall"
    log ""
  end
  log "" & beerCount & " " & bottles & " of beer on the wall"
  log "" & beerCount & " " & bottles & " of beer"
  log "Take one down, pass it around"
end
log "No more bottles of beer on the wall!"


bottle(x):
  template: '
  $x bottles of beer on the wall.
  $x bottles of beer.
  Take one down and pass it around,
  $y bottles of beer on the wall.
  '

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

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

99bottles():
  bottles(99) -> io


use std

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


IT'S SHOWTIME
HEY CHRISTMAS TREE is0
YOU SET US UP @NO PROBLEMO
HEY CHRISTMAS TREE bottles
YOU SET US UP 99
STICK AROUND is0
TALK TO THE HAND bottles
TALK TO THE HAND " bottles of beer on the wall"
TALK TO THE HAND bottles
TALK TO THE HAND " bottles of beer"
TALK TO THE HAND "Take one down, pass it around"
GET TO THE CHOPPER bottles
HERE IS MY INVITATION bottles
GET DOWN 1
ENOUGH TALK
TALK TO THE HAND bottles
TALK TO THE HAND " bottles of beer on the wall"
GET TO THE CHOPPER is0
HERE IS MY INVITATION bottles
LET OFF SOME STEAM BENNET 0
ENOUGH TALK
CHILL
YOU HAVE BEEN TERMINATED


s: "s"

loop 99..1 'i [
    print ~"|i| bottle|s| of beer on the wall,"
    print ~"|i| bottle|s| of beer"
    print ~"Take one down, pass it around!"
    if 1=i-1 -> s: ""

    if? i>1 [
        print ~"|i-1| bottle|s| of beer on the wall!"
        print ""
    ]
    else -> print "No more bottles of beer on the wall!"
]


 /-99#-.
/>*$_#-$_" bottles of beer on the wall, "-$_#-$" bottles of beer."\
|[-]1#-----" ,dnuora ti ssap dna nwod eno ekaT"_$-----------------/
| |
| | &-".llaw eht no reeb fo selttob 99 ,erom emos yub dna erots eht ot oG"$\
| |/$""-$"No more bottles of beer on the wall, no more bottles of beer."---/
| |\".llaw eht no reeb fo selttob erom on ,dnuora ti ssap dna nwod eno ekaT"$-".reeb fo elttob 1"$\
| |          /-$"1 bottle of beer on the wall."-$""-$_"1 bottle of beer on the wall, "------------/
| | /-------\|
| \-*--{=}-\\~$_#-$" bottles of beer on the wall."\
|   \-#1/  \-/                                    |
\----------------------------------------------""$/


fun bottles(n): match __args__:
    (0) => "No more bottles"
    (1) => "1 bottle"
    (_) => "$n bottles"

for n in 99..-1..1:
    print @format"""
    {bottles n} of beer on the wall
    {bottles n} of beer
    Take one down, pass it around
    {bottles n-1} of beer on the wall\n
    """


// Rosetta Code problem: http://rosettacode.org/wiki/99_bottles_of_beer
// by Jjuanhdez, 05/2022

int bottles = 99;

for (int i = bottles; i > 0; --i) {
    write(string(i), " bottles of beer on the wall,");
    write(string(i), " bottles of beer.");
    write("Take one down and pass it around,");
    if (i == 1) {
        write("no more bottles of beer on the wall...");
    } else {
        write(string(i-1), " bottles of beer on the wall...");
    }
}

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


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


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


99→B
While 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


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


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 section
var x 1024

// Write two digits, based on the value in a
fun 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)
    end
end

// vim: set syntax=c ts=4 sw=4 et:


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


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)


  >       NN      p
> d#_8~2~(P~3~.~1~>{` bottles of beer on the wall, `{` bottles of beer.`q
d`.llaw eht no reeb fo selttob `{pLM` ,dnuora ti ssap dna nwod eno ekaT`N<
q`.llaw eht no reeb fo elttob ` {<
 >        NN       >{` bottle of beer on the wall, `{` bottle of beer.`N  q
pN `.llaw eht no reeb fo selttob erom on ,dnuora ti ssap dna nwod eno ekaT`<
>N`No 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`<


local bot:int = 99

repeat
    print string(bot)+" bottles of beer on the wall,"
    print string(bot)+" bottles of beer."
    print "Take one down, pass it around,"
    bot:-1
    print string(bot)+" bottles of beer on the wall."
    print
until bot = 1

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


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


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.


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


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


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


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


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


shared void ninetyNineBottles() {

	String bottles(Integer count) =>
			"``count == 0 then "No" else count``
			 bottle``count == 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 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 lyrics
var LyricsSpace: domain(1) = {1..numVerses};

// array of lyrics
var Lyrics: [LyricsSpace] string;

// parallel computation of lyrics array
[verse in LyricsSpace] Lyrics(verse) = computeLyric(verse);

// as in any good parallel language, I/O to stdout is serialized.
// (Note that I/O to a file could be parallelized using a parallel
// prefix computation on the verse strings' lengths with file seeking)
writeln(Lyrics);

// HELPER FUNCTIONS:

proc computeLyric(verseNum) {
  var bottleNum = numBottles - (verseNum - 1);
  var nextBottle = (bottleNum + numVerses - 1)%numVerses;
  return "\n" // disguise space used to separate elements in array I/O
       + describeBottles(bottleNum, startOfVerse=true) + " on the wall, "
       + describeBottles(bottleNum) + ".\n"
       + computeAction(bottleNum)
       + describeBottles(nextBottle) + " on the wall.\n";
}

proc describeBottles(bottleNum, startOfVerse:bool = false) {
// NOTE: bool should not be necessary here (^^^^); working around bug
  var bottleDescription = if (bottleNum) then bottleNum:string
                                         else (if startOfVerse then "N"
                                                               else "n")
                                              + "o more";
  return bottleDescription
       + " bottle" + (if (bottleNum == 1) then "" else "s")
       + " of beer";
}

proc computeAction(bottleNum) {
  return if (bottleNum == 0) then "Go to the store and buy some more, "
                             else "Take one down and pass it around, ";
}


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


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


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'


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


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


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")
    end
end 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");
    end
end 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))
    end
end start_up


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.


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]


<cfoutput>
  <cfloop index="x" from="99" to="0" step="-1">
    <cfset plur = iif(x is 1,"",DE("s"))>
    #x# bottle#plur# of beer on the wall

    #x# bottle#plur# of beer

    Take one down, pass it around

    #iif(x is 1,DE("No more"),"x-1")# bottle#iif(x is 2,"",DE("s"))# of beer on the wall

  </cfloop>
</cfoutput>


0010 DIM itone$(0:1)
0020 itone$(0):="one";itone$(1):="it"
0030 FOR b#:=99 TO 1 STEP -1 DO
0040   bottles(b#)
0050   PRINT "of beer on the wall,"
0060   bottles(b#)
0070   PRINT "of beer,"
0080   PRINT "Take ",itone$(b#=1)," down and pass it around,"
0090   bottles(b#-1)
0100   PRINT "of beer on the wall!"
0110   PRINT
0120 ENDFOR b#
0130 PROC bottles(b#) CLOSED
0140   CASE b# OF
0150   WHEN 0
0160     PRINT "No more bottles ",
0170   WHEN 1
0180     PRINT "1 bottle ",
0190   OTHERWISE
0200     PRINT b#," bottles ",
0210   ENDCASE
0220 ENDPROC bottles
0230 END


bottles = ' bottles '
remaining = 99
one_less_bottle = remaining
depluralize
  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 wall`n'
  remaining = remaining - 1

  comefrom if one_less_bottle is 0
  'No more bottles of beer on the wall'


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;


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"


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


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

}


[
  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

dnrpsA
dnlBP
lCP
1-
dn[ bottle of beer on the wall]p
rdnrpsA
n[ bottle of beer
]P
[Take it down, pass it around
]P
[no more bottles of beer on the wall
]P


;
;===============================================================================
;       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 99
A2,     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


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") fi
corp;

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) od
corp


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


Module: bottles
define method bottles (n :: <integer>)
  for (n from 99 to 1 by -1)
    format-out("%d bottles of beer on the wall,\n"
               "%d bottles of beer\n"
               "Take one down, pass it around\n"
               "%d bottles of beer on the wall\n",
               n, n, n - 1);
  end
end method


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


;
;===============================================================================
========================
;       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 LINE2
BNUMBOTTLES, A2
,    A32, " Bottles of Beer,"

RECORD LINE3
CNUMBOTTLES, A2
,    A32, " Bottles of Beer on the wall."

RECORD LINE4
DNUMBOTTLES, A2
,    A32, " Bottle of Beer on the wall,"

RECORD LINE5
ENUMBOTTLES, 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


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


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


import "prelude.eg"
import "io.ego"

using System
using 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


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


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


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]


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
}


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


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


(let ((i 99))
  (while (> i 0)
    (message "%d bottles of beer on the wall" i)
    (message "%d bottles of beer" i)
    (message "Take one down, pass it around")
    (message "%d bottles of beer on the wall" (1- i))
    (setq i (1- i))))


-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, 99
bottles 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 of
beer 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.


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


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


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


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


uses "console";

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

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

	looping = counter.invoke();

	Console.println("${bottles} bottles of beer on the wall.");


\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


: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


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


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"


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"


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


include "NSLog.incl"

NSUInteger  i
CFStringRef 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 -1
  NSLog( @"%ld%@%ld%@%@%ld%@\n", i, a, i, b, c, i -1, a )
next

HandleEvents


' 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


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;


[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


if (!exists("bottles")) bottles = 99
print sprintf("%i bottles of beer on the wall", bottles)
print sprintf("%i bottles of beer", bottles)
print "Take one down, pass it around"
bottles = bottles - 1
print sprintf("%i bottles of beer on the wall", bottles)
print ""
if (bottles > 0) reread


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


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


[296,{3/)}%-1%["No more"]+[" bottles":b]294*[b-1<]2*+[b]+[" of beer on the wall\n".8<"\nTake one down, pass it around\n"+1$n+]99*]zip


module Bottles

augment java.lang.Integer {
	function bottles = |self| -> match {
		when self == 0 then "No bottles"
		when self == 1 then "One bottle"
		otherwise self + " bottles"
	}
}

function main = |args| {
	99: downTo(1, |i| {
		println(i: bottles() + " of beer on the wall,")
		println(i: bottles() + " of beer!")
		println("Take one down, pass it around,")
		println((i - 1): bottles() + " of beer on the wall!")
		println("--------------------------------------")
	})
}


for (i in 99..0) {

    print("${i} bottles of beer on the wall")

    if (i > 0) {
        print("${i} bottles of beer")
        print("Take one down, pass it around")
    }
    print("");

}


def bottles = { "${it==0 ? 'No more' : it} bottle${it==1 ? '' : 's' }" }

99.downto(1) { i ->
    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
"""
}


$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!";
}


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"


class RosettaDemo
{
    static public function main()
    {
        singBottlesOfBeer(100);
    }

    static function singBottlesOfBeer(bottles : Int)
    {
        var plural : String = 's';

        while (bottles >= 1)
        {
            Sys.println(bottles + " bottle" + plural + " of beer on the wall,");
            Sys.println(bottles + " bottle" + plural + " of beer!");
            Sys.println("Take one down, pass it around,");
            if (bottles - 1 == 1)
            {
                plural = '';
            }

            if (bottles > 1)
            {
                Sys.println(bottles-1 + " bottle" + plural + " of beer on the wall!\n");
            }
            else
            {
                Sys.println("No more bottles of beer on the wall!");
            }
            bottles--;
        }
    }
}


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 + " " + location
endfun

fun take amount location
  return "Take " + amount + " " + location
endfun

fun pass entity destination
  return ", pass " + entity + " " + destination
endfun

let amount 99
while 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


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


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 parameters
BottlesOfBeer;


:-  %say
|=  [* * [bottles=_99 ~]]
:-  %noun
^-  wall
=/  output  `(list tape)`~
|-
?:  =(1 bottles)
  %-  flop
  :-  "1 bottle of beer on the wall"
  :-  "Take one down, pass it around"
  :-  "1 bottle of beer"
  :-  "1 bottle of beer on the wall"
      output
%=  $
  bottles  (dec bottles)
  output
  :-  "{<bottles>} bottles of beer on the wall"
  :-  "Take one down, pass it around"
  :-  "{<bottles>} bottles of beer"
  :-  "{<bottles>} bottles of beer on the wall"
      output
==


dec app  :( list ( char ) X list ( char )) -> list ( char ) ;
dec i2c  : num -> char;
dec i2s  : num -> list(char);
dec beer : num -> list(char);

--- app ( nil , w )
       <= w  ;
--- app (( a  ::  v ), w )
       <=( a  ::  app ( v , w )) ;

--- i2c(0) <= '0';
--- i2c(1) <= '1';
--- i2c(2) <= '2';
--- i2c(3) <= '3';
--- i2c(4) <= '4';
--- i2c(5) <= '5';
--- i2c(6) <= '6';
--- i2c(7) <= '7';
--- i2c(8) <= '8';
--- i2c(9) <= '9';

--- i2s(x) <= if x < 10 then [i2c(x)] else
				app(i2s(x div 10), i2s( x mod 10));

--- beer(x) <= if x = 1 then app( i2s(x),
				" bottle of beer. No more beer on the wall.")
                	else app( app( app( app( app(
				i2s(x),
				" bottles of beer on the wall, "),
				i2s(x)),
				" bottles of beer. "),
				"Take one down, pass it around. "),
				beer(y))
                        where y== x-1;


#! /bin/sh
exec 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 );
}


on BeerSong99
  BottlesOfBeer 99
end BeerSong99

on OutputBeerLyric beerString
  if ( beerString is "<reset>" ) then
    put empty into cd fld "beer song"
  else
    put beerString & return after cd fld "beer song"
  end if
end OutputBeerLyric

on BottlesOfBeer bottleCount
  put bottleCount into initialCount
  OutputBeerLyric "<reset>"

  repeat until ( bottleCount < 1 )
    set cursor to busy     -- let 'em know this might take a while
    put BottleString(bottleCount) into currentString
    OutputBeerLyric currentString && "of beer on the wall,"
    OutputBeerLyric currentString && "of beer."
    OutputBeerLyric "Take one down, and pass it around,"

    subtract one from bottleCount
    OutputBeerLyric BottleString(bottleCount) && "of beer on the wall." & return
  end repeat

  OutputBeerLyric "Go to the store and buy some more..."
  OutputBeerLyric initialCount & " bottles of beer on the wall."
end BottlesOfBeer

function BottleString bottleCount
  if ( bottleCount is 1 ) then
    return "1 bottle"
  else if ( bottleCount is 0 ) then
    return "no more bottles"
  else
    return bottleCount && "bottles"
  end if
end BottleString


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


Pro bottles

for i=1,99 do begin
 print, 100-i, " bottles of beer on the wall.", 100-i, $
 " bottles of beer.", " Take one down, pass it around," , $
 99-i, " bottles of beer on the wall."
endfor
End


beerSong : Fin 100 -> String
beerSong x = verses x where

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

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

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


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


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.


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


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
)


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


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


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