CIS 1057: Homework 3

Handed out: 09/14/2010
Due: 10am on 09/20/2010
Email program to TA

Write a program that interacts with the user as follows: The program asks the user to think of an integer between 1 and 100. Then it goes in a question and answer session. The questions from the computer are always of the same form:

      Is the number less than or equal to X?
where X may be any number between 1 and 100. The user replies with the integer 1 for yes and 0 for no. Finally the computer will print out its guess [it will always be right] and terminate.

Hints

Below is an algorithm you can use for this homework:

  We use the integer variables low, initialized to 1, high, 
  initialized to 100, middle, and answer.

  We repeat doing the following:
    Set middle to the mid point between low and high.
    Ask the user if the number they are thinking of is less than
    or equal to middle.
    if the answer is 1 then
       Set high to middle
    otherwise
       Set low to middle+1
  until low becomes equal or greater than high.
  Now you can announce the hidden number: It is low.

The output from tracing the algorithm for the number 45 is:

Is the number less than or equal to 50? 1
Is the number less than or equal to 25? 0
Is the number less than or equal to 38? 0
Is the number less than or equal to 44? 0
Is the number less than or equal to 47? 1
Is the number less than or equal to 46? 1
Is the number less than or equal to 45? 1
The number is 45
and the values of low, high, and middle in the various iterations are:
low: 1 high: 100 middle: 50
low: 1 high: 50 middle: 25
low: 26 high: 50 middle: 38
low: 39 high: 50 middle: 44
low: 45 high: 50 middle: 47
low: 45 high: 47 middle: 46
low: 45 high: 46 middle: 45
Test your program with various input values and insert in your program a comment indicating the values you have tested.