Listing 2 A C program to play HI-LO

/* The game of HI-LO - your number in 7
guesses */

#include <stdio.h>
#include <ctype.h>

main()
{

   int done 0;         /* Control flag */

   puts("Think of a number between 1 and 100.");
   puts("If you don't cheat, I'll figure it out");
   puts("in seven guesses or less!\n");

   while (!done)
   {
      int found = 0;  /* Control Flag */
      int lo = 1, hi = 100;
      int guess;
      char response;

      /* Play the Game */
      while (!found && lo <= hi)
      {
         /* Get response */
         guess = (lo + hi) / 2;
         printf("Is it %d (L/H/Y): ",guess);
         fflush(stdout);
         scanf("%c%*c",&response);
         response = toupper(response);

         /* Narrow the search range */
         if (response == 'L')
            lo = guess + 1;
         else if (response == 'H')
            hi = guess - 1;
         else if (response != 'Y')
            puts("What? Try again...");
         else
            found = 1;
      }

      /* Print results */
      if (lo > hi)
         puts("You cheated!");
      else
      {
         printf("Your number was %d\n",guess);
         puts("What fun!");
      }

      printf("Wanna play again? ");
      fflush(stdout);
      scanf("%c%*c",&response);
      if (toupper(response) != 'Y')
         done = 1;
   }
   return 0;
}

/* Sample Execution (numbers are 37 and 99)
c:>hi-lo
Think of a number bewteen 1 and 100.
If you don't cheat, I'll figure it out
in seven guesses or less!

Is it 50 (L/H/Y): h
Is it 25 (L/H/Y): l
Is it 37 (L/H/Y): y
Your number was 37
What fun!
Wanna play again? y
Is it 50 (L/H/Y): l
Is it 75 (L/H/Y): l
Is it 88 (L/H/Y): l
Is it 94 (L/H/Y): l
Is it 97 (L/H/Y): l
Is it 99 (L/H/Y): l
Is it 100 (L/H/Y): h
You cheated!
Wanna play again? n
*/

/* End of File */