# Classwork 7: I am Thinking of a Number

## Objectives

To practice writing a program that uses if statements and a while loop.

## The Assignment

Write a program to play the game "I'm thinking of a number." The program will play the role of the person who has the "secret" number. Your program should prompt the user to guess a number. If user's guess is incorrect, your program should say whether the guess is too high or too low. A sample run of your program might look like the following (with the user response in orange):

```
PT[321]% gcc -Wall thinking.c

PT[322]% ./a.out
I'm thinking of a number between 1 and 100.
Guess my number.
Too low!
Too low!
Too low!
Too high!
Too high!
Too low!
Too high!
Too low!
Too high!
Too high!
Too low!
You got it!
PT[323]%

```

## Notes

You must use a while loop in your program which terminates when the user guesses the correct number.

Use #define to define a constant secret that holds the number your program is "thinking" of. (See for example math.c which used #define to define a constant PI.) That way, if you change the secret number, you only have to change it in one place.

Name your program thinking.c. Use the script command to record yourself compiling the program using and testing your program in several sample runs. (Remember to exit from script when you are done. Also, do not run nano when you are in script.) Finally, submit your program and sample runs using:

```
submit cs104_chang cw07 thinking.c
submit cs104_chang cw07 typescript

```

## Embellishments (optional)

Include any number of the following embellishments, if you have time:

• Warn the user if he enters a number less than 1 or a number greater than 100.

• Instead of picking the same secret number each time, use a pseudo-random generator function. To do so, you must include the following header files:

```
#include <stdlib.h>
#include <time.h>
```

The first statement in your main function should set the random seed, as follows:

```
srandom(time(0)) ;
```

The time function returns the number of seconds since 00:00:00 UTC, January 1, 1970. So, each run of the program (started more than 1 second apart) will set then random seed to a different value.

Now each call to the function random() will return a "pseudo-random" number as an int value. To convert this into a number that is within the range of allowed numbers, use the % mod operator:

```
n = random() % 100 + 1 ;
```

Then no matter what random returns, the variable n is assigned a number between 1 and 100.

• Ask the user for the range of numbers from which to choose the secret number (instead of always choosing a number between 1 and 100). This will affect how you implement the other embellishments.