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 (
A true
Figure 6.1. The structure of if statements.
Most often,
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
if (
else
If
if (answer == 1492)
cout << "That's right!\n";
else
cout << "You'd better review Chapter 1 again.\n";