< previous page page_203 next page >

Page 203
0203-01.gif
Figure 5-3
If-Then-Else Flow of Control
if (hours <= 40.0)
    pay = rate * hours;
else
    pay = rate * (40.0 + (hours - 40.0) * 1.5);
cout << pay;
In terms of instructions to the computer, the above code fragment says, If hours is less than or equal to 40.0, compute the regular pay and then go on to execute the output statement. But if hours is greater than 40, compute the regular pay and the overtime pay, and then go on to execute the output statement. Figure 5-4 shows the flow of control of this If statement.
If-Then-Else often is used to check the validity of input. For example, before we ask the computer to divide with a data value, we should be sure that the value is not zero. (Even computers can't divide something by zero. If you try, the computer halts the execution of your program.) If the divisor is zero, our program should print out an error message. Here's the code:
if (divisor != 0)
    result = dividend / divisor;
else
    cout << Division by zero is not allowed. << endl;
Before we look any further at If statements, take another look at the syntax template for the If-Then-Else. According to the template, there is no semicolon at the end of an If statement. In both of the program fragments

 
< previous page page_203 next page >