| I l @ ve RuBoard |
6.1 if StatementThe if statement allows you to put some decision-making into your programs. The general form of the if statement is: if ( condition ) statement; If the expression is true (nonzero), the statement is executed. If the expression is false (zero), the statement is not executed. For example, suppose you are writing a billing program. At the end, if the customer owes nothing or if he has credit (owes a negative amount), you want to print a message. In C++ this is written:
if (total_owed <= 0)
std::cout << "You owe nothing.\n";
The operator <= is a relational operator that represents less than or equal to. This statement reads, "If the total_owed is less than or equal to zero, print the message." The complete list of relational operators is found in Table 6-1. Table 6-1. Relational operators
Multiple relational expressions may be grouped together with logical operators . For example, the statement:
if ((oper_char == 'Q') (oper_char == 'q'))
std::cout << "Quit\n";
uses the logical OR operator ( ) to cause the if statement to print "Quit" if oper_char is either a lowercase "q" or an uppercase "Q". Table 6-2 lists the logical operators. Table 6-2. Logical operators
Multiple statements after the
if
may be grouped by
if (total_owed <= 0) {
++zero_count;
std::cout << "You owe nothing.\n";
}
For readability, the statements
|
| I l @ ve RuBoard |
| I l @ ve RuBoard |
6.2 else StatementAn alternative form of the if statement is: if ( condition ) statement ; else statement ; If the condition is true, the first statement is executed. If it is false, the second statement is executed. In our accounting example, we wrote out a message only if nothing was owed. In real life, we probably want to tell the customer how much he owes if there is a balance due.
if (total_owed <= 0)
std::cout << "You owe nothing.\n";
else
std::cout << "You owe " << total_owed << " dollars\n";
Now consider this program fragment:
if (count < 10) // If #1
if ((count % 4) == 2) // If #2
std::cout << "Condition:White\n";
else // (Indentation is wrong)
std::cout << "Condition:Tan\n";
There are two if statements and one else . To which if does the else belong? Pick one:
The correct answer is 3. According to the C++ syntax rules, the
else
goes with the
if (count < 10) { // If #1
if ((count % 4) == 2) // If #2
std::cout << "Condition:White\n";
else
std::cout << "Condition:Tan\n";
}
From our original example, it was not clear which
if
statement had the
else
clause; however, adding an extra set of braces
|
| I l @ ve RuBoard |