- 4.1 Introduction
- 4.2 Control Structures
- 4.3 if Selection Statement
- 4.4 if...else Double-Selection Statement
- 4.5 while Repetition Statement
- 4.6 Counter-Controlled Repetition
- 4.7 Sentinel-Controlled Repetition
- 4.8 Nested Control Statements
- 4.9 Assignment Operators
- 4.10 Increment and Decrement Operators
- 4.11 (Optional) Software Engineering Case Study: Identifying Class Attributes in the ATM System
- 4.12 Wrap-Up
4.3 if Selection Statement
Programs use selection statements to choose among alternative courses of action. For example, suppose the passing grade on an exam is 60. The statement
if ( grade >= 60 ) cout << "Passed";
determines whether the condition grade >= 60 is true or false. If it is true, "Passed" is printed and the next statement in order is performed. If the condition is false, the printing is ignored and the next statement in order is performed. Note that the second line of this selection statement is indented. Such indentation is optional, but recommended.
Figure 4.3 illustrates the single-selection if statement. It contains what is perhaps the most important symbol in an activity diagram—the diamond or decision symbol, which indicates that a decision is to be made. A decision symbol indicates that the workflow will continue along a path determined by the symbol's associated guard conditions, which can be true or false. Each transition arrow emerging from a decision symbol has a guard condition (specified in square brackets above or next to the transition arrow). If a particular guard condition is true, the workflow enters the action state to which that transition arrow points. In Fig. 4.3, if the grade is greater than or equal to 60, the program prints "Passed" to the screen, then transitions to the final state of this activity. If the grade is less than 60, the program immediately transitions to the final state without displaying a message.
Fig. 4.3 if single-selection statement activity diagram.
In C++, a decision can be based on any expression—if the expression evaluates to zero, it is treated as false; if the expression evaluates to nonzero, it is treated as true. C++ provides the data type bool for variables that can hold only the values true and false—each of these is a C++ keyword.