Number Guessing Game in Eleven Languages

Objective:  Create a number guessing game, where the user picks an integer (whole positive number) from 1 to 100.  If the user guesses incorrectly, then they will be told if the correct answer is higher or lower.  The user keeps guessing until they enter the correct answer.

Concepts covered:

  • User input from STDIN
  • IF/ELSE IF conditionals
  • WHILE loops
  • random integer generation

Constraints:  Only languages that are available in Ubuntu 11.04 or the Synaptic repository are included.

C

# vi guess.c

#include <stdio.h>
#include <time.h>

int main(void) {
  int iGuess;
  int iGuessCount;
  int iAnswer;

  srand(time(NULL));

  iGuess = -1;
  iGuessCount = 0;
  iAnswer = (rand() % 100) + 1; 

  while (iGuess != iAnswer) {
    printf("Guess the number\n");
    scanf("%d", &iGuess);
    iGuessCount++;

    if (iGuess > iAnswer) {
      printf("Lower\n");
    } else if (iGuess < iAnswer) {
      printf("Higher\n");
    } else if (iGuess == iAnswer) {
      printf("Correct: %d\n", iAnswer);
      printf("%d total guesses\n", iGuessCount);
    }

  }

  return 0;
}

# gcc guess.c -o guess

# ./guess

C++

# vi guess.cpp

#include <iostream>
#include <cstdlib>

using namespace std;

int main(void) {
  int iGuess;
  int iGuessCount;
  int iAnswer;

  srand(time(NULL));

  iGuess = -1;
  iGuessCount = 0;
  iAnswer = (rand() % 100) + 1;

  while (iGuess != iAnswer) {
    cout << "Guess the number" << endl;
    cin >> iGuess;

    iGuessCount++;

    if (iGuess > iAnswer) {
      cout << "Lower" << endl;
    } else if (iGuess < iAnswer) {
      cout << "Higher" << endl;
    } else if (iGuess == iAnswer) {
      cout << "Correct: " << iAnswer << endl;
      cout << iGuessCount << " total guesses" << endl;
    }

  }

  return 0;

}

# g++ guess.cpp -o guess

# ./guess

Java

# vi Guess.java

import java.util.Random;
import java.io.*;

public class Guess {

  public Guess() {
    int iGuess;
    int iGuessCount;
    int iAnswer;
    String strLine;

    iGuess = -1;
    iGuessCount = 0;
    iAnswer = (Math.abs((new Random()).nextInt()) % 100) + 1;

    try {

      BufferedReader in = new BufferedReader(
                            new InputStreamReader(System.in));
      while (iGuess != iAnswer) {
        System.out.println("Guess the number");
        strLine = in.readLine();

        try {
          iGuess = Integer.parseInt(strLine);
          iGuessCount++;

          if (iGuess > iAnswer) {
            System.out.println("Lower");
          } else if (iGuess < iAnswer) {
            System.out.println("Higher");
          } else if (iGuess == iAnswer) {
            System.out.println("Correct " + iAnswer);
            System.out.println(iGuessCount + " total guesses");
          }

        } catch (NumberFormatException e2) {
          System.out.println("Invalid Input");
        }
      }
    } catch (IOException e1) {
      e1.printStackTrace();
    }

  }

  public static void main(String args[]) {
    new Guess();
  }

}

# javac Guess.java

# java Guess

Ruby

# vi guess.rb

iGuess = -1
iGuessCount = 0
iAnswer = 1 + rand(100)

while (iGuess != iAnswer)
  puts "Guess the number"
  iGuess = gets().to_i
  iGuessCount += 1

  if (iGuess > iAnswer)
    puts "Lower"
  elsif (iGuess < iAnswer)
    puts "Higher"
  elsif (iGuess == iAnswer)
    puts "Correct: #{iAnswer}"
    puts "#{iGuessCount} total guesses"
  end

end

# ruby guess.rb

Perl

# vi guess.pl

$iGuess = -1;
$iGuessCount = 0;
$iAnswer = int(rand(100)) + 1;

while ($iGuess != $iAnswer) {
  print "Guess the number" . "\n";
  $iGuess = <STDIN>;
  $iGuessCount += 1;

  if ($iGuess > $iAnswer) {
    print "Lower" . "\n";
  } elsif ($iGuess < $iAnswer) {
    print "Higher" . "\n";
  } elsif ($iGuess == $iAnswer) {
    print "Correct: " . $iAnswer . "\n";
    print $iGuessCount . " total guesses" . "\n";
  }
}

# perl guess.pl

SmallTalk (Squeak)

| iGuess iGuessCount iAnswer |

iGuess := -1.
iGuessCount := 0.
iAnswer := (1 to: 100) atRandom.

[ (iGuess ~= iAnswer) ]
whileTrue: [

  iGuess := FillInTheBlankMorph request: 'Guess the number'.
  iGuess := iGuess asNumber.
  iGuessCount := iGuessCount + 1.

  (iGuess > iAnswer)
  ifTrue: [
    Transcript show: 'Lower'.
    Transcript cr.
  ].

  (iGuess < iAnswer)
  ifTrue: [
	Transcript show: 'Higher'.
	Transcript cr.
  ].

  (iGuess = iAnswer)
  ifTrue: [
    Transcript show: 'Correct: '.
    Transcript show: iAnswer.
    Transcript cr.
    Transcript show: iGuessCount.
    Transcript show: ' total guesses'.
    Transcript cr.
  ].
].

With code in a Transcript window, select text, then “Do It” (Alt-D)

Python

# vi guess.py

import random
import sys

iGuess = -1
iGuessCount = 0
iAnswer = random.randint(1, 100)

while iGuess != iAnswer:
  print "Guess the number"
  iGuess = input()
  iGuessCount += 1

  if iGuess > iAnswer:
    print "Lower"
  elif iGuess < iAnswer:
    print "Higher"
  elif iGuess == iAnswer:
    print("Correct: " + str(iAnswer))
    print(str(iGuessCount) + " total guesses")

# python guess.py

FORTRAN 77

# vi guess.f

       program guess
       integer iGuess, iGuessCount, iAnswer

       iGuess = -1
       iGuessCount = 0
       call srand(time())
       iAnswer = irand(0)
       iAnswer = mod(iAnswer, 100) + 1

10     if (iGuess.NE.iAnswer) then

         print *, 'Guess the number'
         read(*,*) iGuess
         iGuessCount = iGuessCount + 1

         if (iGuess.GT.iAnswer) then
           print *, 'Lower'
         end if

         if (iGuess.LT.iAnswer) then
           print *, 'Higher'
         end if

         if (iGuess.EQ.iAnswer) then
           print *, 'Correct: ', iGuess
           print *, iGuessCount, ' total guesses'
         end if

       goto 10
       endif

       stop
       end

# gfortran guess.f -o guess

# ./guess

Scala

# vi Guess.scala

import scala.util.Random

object Guess {

  def start() = {
    var iGuess = -1
    var iGuessCount = 0
    var iAnswer =  (new Random()).nextInt(100) + 1

    while (iGuess != iAnswer) {
      println("Guess the number")
      iGuess = readInt
      iGuessCount += 1

      if (iGuess > iAnswer) {
        println("Lower")
      } else if (iGuess < iAnswer) {
        println("Higher")
      } else if (iGuess == iAnswer) {
        println("Correct: " + iAnswer)
        println(iGuessCount + " total guesses")
      }
     }
  }

  def main(args: Array[String]) {
    this.start()
  }
}

# scalac Guess.scala

# scala Guess

PHP

# vi guess.php

<?php

  $iGuess = -1;
  $iGuessCount = 0;
  $iAnswer = rand(1, 100);

  while ($iGuess != $iAnswer) {
    echo "Guess the number\n";
    $iGuess = trim(fgets(STDIN));
    $iGuessCount++;

    if ($iGuess > $iAnswer) {
      echo "Lower\n";
    } elseif ($iGuess < $iAnswer) {
      echo "Higher\n";
    } elseif ($iGuess == $iAnswer) {
      echo "Correct: " . $iAnswer . "\n";
      echo $iGuessCount . " total guesses\n";
    } 

  }
?>

# php guess.php

bash script

# vi guess.sh

#!/bin/bash

iGuess=-1
iGuessCount=0
iAnswer=$(( ($RANDOM % 100) + 1))

while [ $iGuess -ne $iAnswer ]
do
  echo "Guess the number"
  read iGuess
  (( iGuessCount++ ))

  if [ $iGuess -gt $iAnswer ]; then
    echo "Lower"
  elif [ $iGuess -lt $iAnswer ]; then
    echo "Higher"
  elif [ $iGuess -eq $iAnswer ]; then
    echo "Correct: $iAnswer"
    echo "$iGuessCount total guesses"
  fi
done

# chmod u+x guess.sh

# ./guess.sh

Output

Guess the number
50
Higher
Guess the number
75
Lower
Guess the number
63
Lower
Guess the number
57
Higher
Guess the number
60
Correct: 60
5 total guesses
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: