|
|
|
|
|
|
|
The method shown so far, testing first one condition and then the other, works fine but is a bit cumbersome. The keyword else can make for far more readable code: |
|
|
|
|
|
|
|
|
if (expression)
statement;
else
statement; |
|
|
|
|
|
|
|
|
Listing 4.3 demonstrates the use of the keyword else. |
|
|
|
|
|
|
|
|
LISTING 4.3 DEMONSTRATING THEelse KEYWORD |
|
|
|
 |
|
|
|
|
1: // Listing 4.3 - demonstrates if statement
2: // with else clause
3: #include <iostream.h>
4: int main()
5: {
6: int firstNumber, secondNumber;
7: cout << Please enter a big number: ;
8: cin >> firstNumber;
9: cout << \nPlease enter a smaller number: ;
10: cin >> secondNumber;
11: if (firstNumber > secondNumber)
12: cout << \nThanks!\n;
13: else
14: cout << \nOops. The second is bigger!;
15:
16: return 0;
17: } |
|
|
|
|
|
|
|
|
Please enter a big number: 10
Please enter a smaller number: 12
Oops. The second is bigger! |
|
|
|
|
|
|
|
|
Analysis: The if statement on line 11 is evaluated. If the condition is true, the statement on line 12 is run; if it is false, the statement on line 14 is run. If the else clause on line 13 were removed, the statement on line 14 would run whether or not the if statement were true. Remember, the if statement ends after line 12. If the else was not there, line 14 would just be the next line in the program. |
|
|
|
|
|
|
|
|
Remember that either or both of these statements could be replaced with a block of code in braces. |
|
|
|
|
|