Solution for Exercise 11-21

ex1121

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

int main()
{
    int r,guess;

    srand((unsigned)time(NULL));
    r=rand();
    printf("Can you guess the secret number: ");
    scanf("%d",&guess);
    if(guess==r)
    {
        puts("You guessed it!");
        return(0);
    }
    if(guess!=r)
    {
        puts("Wrong!");
        printf("The secret number was %d\n",r);
        return(1);
    }
}

Notes

* You don't need to #define SECRET 17 in this code because the random number generator, the rand() function, produces the secret number for you. (Reference Exercise 8-6 to see what I mean.)

* Yep, you'll probably never guess the random number because it's in the range for an int variable, which goes into the millions, both positive and negative.

* Fix Number One: Use the modulus operator to narrow down the number to the range of 1 to 10.

* Fix Number Two: Put the guessing part of the program into a loop that gives the user three chances to guess the number in the range 1 to 10. After each guess, let them know whether the number is higher or lower.