Solution for Exercise 8-6

ex0806

#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);
    }
    if(guess!=secret)
    {
        puts("Wrong!");
        return(1);
    }
}

Output

Can you guess the secret number: 8
Wrong!

Notes

* Technically, the program doesn't need a final return statement (after the last if decision). Both if statements' conditions evaluated are absolute, so one or the other is executed. The return belonging to either if statement is enough to end execution. A final return would be superfluous. Even so:

* The compiler may warn you that main() is an int function and it requires a return statement near its bottom. That's an example of one of those warnings you can freely ignore — but only when you understand that in a program like this, logic shows how a final return statement isn't necessary.

* You can stick a return anywhere in a function, well, anywhere that's logical. For example, an if expression could determine whether the function is done and use a return to end the function. But when the condition isn't met, the rest of the function runs. In this case, a final return is necessary — especially in the main() function to return an integer value to the operating system.