Solution for Exercise 11-21

ex1121

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

int main()
{
    int secret,guess;

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

Output

Can you guess the secret number: 9765431
Wrong!
The secret number was 778809536

Notes

* Refer to Exercise 8-6 to see the original.

* See how I replaced the second if statement with an else? You know this now.

* 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. (See this blog post.)