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);
}

Output

Do you want to continue (Y/N): Perhaps
You didn't type Y or N!

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.

* In Line 8, I used scanf() though you could just as 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, the program displays Continuing... regardless of which key was pressed. This is because the single equal sign is an assignment, which would be true for any character input.

* 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 need not match mine, and it's okay to use printf() instead of puts().

* Because each part of the if-else if-else structure holds only one statement, the curly brackets are not required. They do make the code more readable.