Solution for Exercise 8-16

ex0816

#include <stdio.h>

int main()
{
    char yorn;

    printf("Do you want to continue (Y/N)? ");
    scanf("%c",&yorn);
    if( yorn == 'Y' || yorn == 'y' )
    {
        puts("Continuing...");
    }
    else if( yorn == 'N' || yorn == 'n' )
    {
        puts("Stopping now.");
    }
    else
    {
        puts("You didn't type Y or N!");
    }
    return(0);
}

Notes

* The key to getting this exercise correct is using the || comparison twice. First for the Y key press and then for the N.

* I used an if-else-if-else structure to handle all three variations. You get bonus points if you thought of that as well.

* The yes-no prompt you use doesn't have to be the same text displayed at Line 7 by the printf() statement.

* In Line 8, I used scanf() instead of getchar() simply to be different; I don't have many scanf() examples in the book where one character is read. You could have easily used getchar().

* The if comparison at Line 9 is important. It uses the logical OR to compare two results for the key read: Y or y. The two equal signs are required for a comparison. If you forgot and used only one equal sign, then the program displays Continuing... regardless of which key was pressed. That's because the single equal sign is an assignment, which is always true.

* The else-if comparison at Line 13 repeats the comparison at Line 9, but for the N or n keys.

* Finally, at Line 17, else picks up the slack and displays a message when the jokers don't type a Y or N.

* The Y or N question is often called a "yorn" by programmers.

* Your text at Lines 15 and 19 doesn't have to match mine, and it's okay to use printf() instead of puts().

* Because each part of the decision structure uses only one statement, the curly brackets are not required. They do make the code more readable.