Sams Teach Yourself C in 21 Days

(singke) #1
13:
14: int main( void )
15: {
16: int guess_value = -1;
17: int number;
18: int nbr_of_guesses;
19: int done = NO;
20:
21: printf(“\n\nGetting a Random number\n”);
22:
23: /* use the time to seed the random number generator */
24: srand( (unsigned) time( NULL ) );
25: number = rand();
26:
27: nbr_of_guesses = 0;
28: while ( done == NO )
29: {
30: printf(“\nPick a number between 0 and %d> “, RAND_MAX);
31: scanf( “%d”, &guess_value ); /* Get a number */
32:
33: nbr_of_guesses++;
34:
35: if ( number == guess_value )
36: {
37: done = YES;
38: }
39: else
40: if ( number < guess_value )
41: {
42: printf(“\nYou guessed high!”);
43: }
44: else
45: {
46: printf(“\nYou guessed low!”);
47: }
48: }
49:
50: printf(“\n\nCongratulations! You guessed right in %d Guesses!”,
51: nbr_of_guesses);
52: printf(“\n\nThe number was %d\n\n”, number);
53:
54: return 0;
55: }

This program is a simple guessing game. You’re trying to find the number that the com-
puter randomly generates. After each guess, the program will tell you if your guess was
high or low. When you guess correctly, you will be congratulated and told how many
guesses it took you.

94 Type & Run 2

LISTINGT&R 2 continued

08 448201x-T&R2 8/13/02 11:20 AM Page 94

Free download pdf