Solution for Exercise 8-12

ex0812

#include <stdio.h>

int main()
{
    const int secret = 17;
    int guess;

    printf("Can you guess the secret number: ");
    scanf("%d",&guess);
    if(guess==secret)
    {
        puts("You guessed it!");
        return(0);
    }
    else
    {
        puts("Wrong!");
        return(1);
    }
}

Output

Can you guess the secret number: 17
You guessed it!

Notes

* The "best solution" I referred to in the book is to change only Line 15. The change is from if(guess!=secret) to else.

* This solution and the solution for Exercise 8-6 are similar, which may make you wonder why bother with the else statement at all. The reason is that by grouping if-else you create a single structure, which is designed to handle only one condition in an absolute way. While some code may contain two separate if statements back-to-back, such a setup represents two different evaluations, not one. This distinction may be too subtle for you to appreciate at this point in your programming experience, but it's the reason why you use if-else instead of two if statements.