6. Branching Statements and Logical Operators

In this chapter you’ll learn about the following:

• The if statement

• The if else statement

• Logical operators: &&, ||, and !

• The cctype library of character functions

• The conditional operator: ?:

• The switch statement

• The continue and break statements

• Number-reading loops

• Basic file input/output

One of the keys to designing intelligent programs is to give them the ability to make decisions. Chapter 5, “Loops and Relational Expressions,” shows one kind of decision making—looping—in which a program decides whether to continue looping. This chapter investigates how C++ lets you use branching statements to decide among alternative actions. Which vampire-protection scheme (garlic or cross) should the program use? What menu choice has the user selected? Did the user enter a zero? C++ provides the if and switch statements to implement decisions, and they are this chapter’s main topics. This chapter also looks at the conditional operator, which provides another way to make a choice, and the logical operators, which let you combine two tests into one. Finally, the chapter takes a first look at file input/output.

The if Statement

When a C++ program must choose whether to take a particular action, you usually implement the choice with an if statement. The if comes in two forms: if and if else. Let’s investigate the simple if first. It’s modeled after ordinary English, as in “If you have a Captain Cookie card, you get a free cookie.” The if statement directs a program to execute a statement or statement block if a test condition is true and to skip that statement or block if the condition is false. Thus, an if statement lets a program decide whether a particular statement should be executed.

The syntax for the if statement is similar to the that of the while syntax:

if (test-condition)

    statement

A true test-condition causes the program to execute statement, which can be a single statement or a block. A false test-condition causes the program to skip statement (see Figure 6.1). As with loop test conditions, an if test condition is type cast to a bool value, so zero becomes false and nonzero becomes true. The entire if construction counts as a single statement.

Figure 6.1. The structure of if statements.

Most often, test-condition is a relational expression such as those used to control loops. Suppose, for example, that you want a program that counts the spaces in the input as well as the total number of characters. You can use cin.get(char) in a while loop to read the characters and then use an if statement to identify and count the space characters. Listing 6.1 does just that, using the period (.) to recognize the end of a sentence.

Listing 6.1. if.cpp

// if.cpp -- using the if statement

#include

int main()

{

    using std::cin;     // using declarations

    using std::cout;

    char ch;

    int spaces = 0;

    int total = 0;

    cin.get(ch);

    while (ch != '.')   // quit at end of sentence

    {

        if (ch == ' ')  // check if ch is a space

            ++spaces;

        ++total;        // done every time

        cin.get(ch);

    }

    cout << spaces << " spaces, " << total;

    cout << " characters total in sentence\n";

    return 0;

}

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

The balloonist was an airhead

with lofty goals.

6 spaces, 46 characters total in sentence

As the comments in Listing 6.1 indicate, the ++spaces; statement is executed only when ch is a space. Because it is outside the if statement, the ++total; statement is executed in every loop cycle. Note that the total count includes the newline character that is generated by pressing Enter.

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!\n";

else

    cout << "You'd better review Chapter 1 again.\n";

Перейти на страницу:

Все книги серии Developer's Library

Похожие книги