guess

This example is a number-guessing game where the computer thinks up a number between 1 and 100. The player then has to guess that number. If the guess is wrong, the computer indicates whether the real numebr is larger or smaller than the guess. On a correct guess, the number of turns needed is printed.

Source code

x = rand(1,100);

print("Guess a number between 1 and 100.\n");

turns = 1;
while (true) {
  print("Your guess? ");
  reply = (int) fgets(stdin);
  if (reply == x) break;
  if (reply  < x) print("Too small.\n");
  if (reply  > x) print("Too big.\n");
  ++turns;
}

print("You needed ", turns, " turns\n");