Homework 6: I am Thinking of a Number (again)
Due: Tuesday 3/13 by 11:59pm
Objectives
More practice with while loops.
The Assignment
Write a program that plays the other side of the game "I'm thinking of a number" from Classwork 7. This time, the user is thinking of a number and your program will "guess".
The strategy that you will use is very similar to the one we used to approximate the square root: sqrt.c.
As in the sqrt.c program, your program should have two variables: lowEnd and highEnd. The loop invariant is that your program "knows" that the user's number is between lowEnd and highEnd inclusively. Initially, lowEnd is 1 and highEnd is 100. Each time your program "guesses" the number half-way between lowEnd and highEnd. If the new guess is low, then the new guess becomes the new lowEnd. If the new guess is high, then the new guess becomes the new highEnd.
For example, a sample run of your program might look like (user's response in orange):
PT[154]% ./a.out Think of a number between 1 and 100. I will guess the number, then tell me if my guess is too high (enter 'h'), too low (enter 'l') or correct (enter 'y' for 'yes'). Is it 50? [(h)igh, (l)ow, (y)es] h Is it 25? [(h)igh, (l)ow, (y)es] l Is it 37? [(h)igh, (l)ow, (y)es] l Is it 43? [(h)igh, (l)ow, (y)es] h Is it 40? [(h)igh, (l)ow, (y)es] h Is it 38? [(h)igh, (l)ow, (y)es] y Yay! I got it! PT[155]%
Optional Embellishments
If you have extra time, consider adding these features to your program:- It is boring to play against a program that makes the same guesses every time. Instead of guessing a number halfway between lowEnd and highEnd, your program can randomly pick a number between lowEnd and highEnd (inclusive). To use the random function, follow the instructions at the end of Classwork 7.
- Accuse the player of cheating if the player doesn't say y even though your program is sure that it has the correct number (since lowEnd equals highEnd).
Notes
- Name your program guess.c
- Use scanf() and char variables to read
in a single character response from the user
(as you did in Homework 4),
like this:
scanf("%c%c", &reply, &cr) ;
The character entered by the user will be stored in reply and the carriage return will be stored in cr. (You will just ignore the cr variable.)
-
You can use == to compare character values. Also,
character constants are in single quotes. So you can use:
if (reply == 'y') { ... }
- To help debugging and to help you see what is happening with your while loop, print out the values of lowEnd and highEnd inside the while loop. Then comment out the print statement in your final version.
What to Submit
Use the script command to record 3 sample runs of your program. Don't forget to exit from script. Then, submit your program and sample run using.
submit cs104_chang hw06 guess.c typescript
Be sure to logout completely when you have finished!