The if else Statement

Whereas an if statement lets a program decide whether a particular statement or block is executed, an if else statement lets a program decide which of two statements or blocks is executed. It’s an invaluable statement for creating alternative courses of action. The C++ if else statement is modeled after simple English, as in “If you have a Captain Cookie card, you get a Cookie Plus Plus, else you just get a Cookie d’Ordinaire.” The if else statement has this general form:

if (test-condition)
    statement1
else
    statement2

If test-condition is true, or nonzero, the program executes statement1 and skips over statement2. Otherwise, when test-condition is false, or zero, the program skips statement1 and executes statement2 instead. So the following code fragment prints the first message if answer is 1492 and prints the second message otherwise:

if (answer == 1492)
    cout << "That's right! ";
else
    cout << "You'd better review Chapter 1 again. ";

Each statement can be either a single statement or a statement block delimited by braces (see Figure 6.2). The entire if else construct counts syntactically as a single statement.

Figure 6.2. The structure of if else statements.

Image

For example, suppose you want to alter incoming text by scrambling the letters while keeping the newline character intact. In that case, each line of input is converted to an output line of equal length. This means you want the program to take one course of action for newline characters and a different course of action for all other characters. As Listing 6.2 shows, if else makes this task easy. The listing also illustrates the std:: qualifier, one of the alternatives to a using directive.

Listing 6.2. ifelse.cpp


// ifelse.cpp -- using the if else statement
#include <iostream>
int main()
{
    char ch;

    std::cout << "Type, and I shall repeat. ";
    std::cin.get(ch);
    while (ch != '.')
    {
        if (ch == ' ')
            std::cout << ch;     // done if newline
        else
            std::cout << ++ch;   // done otherwise
        std::cin.get(ch);
    }
// try ch + 1 instead of ++ch for interesting effect
    std::cout << " Please excuse the slight confusion. ";
        //  std::cin.get();
        //  std::cin.get();
    return 0;
}


Here’s some sample output from the program in Listing 6.2:

Type, and I shall repeat.
An ineffable joy suffused me as I beheld
Bo!jofggbcmf!kpz!tvggvtfe!nf!bt!J!cfifme
the wonders of modern computing.
uif!xpoefst!pg!npefso!dpnqvujoh
Please excuse the slight confusion.

Note that one of the comments in Listing 6.2 suggests that changing ++ch to ch+1 has an interesting effect. Can you deduce what it will be? If not, try it out and then see if you can explain what’s happening. (Hint: Think about how cout handles different types.)

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.142.42.176