if else if else
ConstructionComputer programs, like life, might present you with a choice of more than two selections. You can extend the C++ if else
statement to meet such a need. As you’ve seen, the else
should be followed by a single statement, which can be a block. Because an if else
statement itself is a single statement, it can follow an else
:
if (ch == 'A')
a_grade++; // alternative # 1
else
if (ch == 'B') // alternative # 2
b_grade++; // subalternative # 2a
else
soso++; // subalternative # 2b
If ch
is not 'A'
, the program goes to the else
. There, a second if else
subdivides that alternative into two more choices. C++’s free formatting enables you to arrange these elements into an easier-to-read format:
if (ch == 'A')
a_grade++; // alternative # 1
else if (ch == 'B')
b_grade++; // alternative # 2
else
soso++; // alternative # 3
This looks like a new control structure—an if else if else
structure. But actually it is one if else
contained within a second. This revised format looks much cleaner, and it enables you to skim through the code to pick out the different alternatives. This entire construction still counts as one statement.
Listing 6.3 uses this preferred formatting to construct a modest quiz program.
// ifelseif.cpp -- using if else if else
#include <iostream>
const int Fave = 27;
int main()
{
using namespace std;
int n;
cout << "Enter a number in the range 1-100 to find ";
cout << "my favorite number: ";
do
{
cin >> n;
if (n < Fave)
cout << "Too low -- guess again: ";
else if (n > Fave)
cout << "Too high -- guess again: ";
else
cout << Fave << " is right!
";
} while (n != Fave);
return 0;
}
Here’s some sample output from the program in Listing 6.3:
Enter a number in the range 1-100 to find my favorite number: 50
Too high -- guess again: 25
Too low -- guess again: 37
Too high -- guess again: 31
Too high -- guess again: 28
Too high -- guess again: 27
27 is right!
Often you must test for more than one condition. For example, for a character to be a lowercase letter, its value must be greater than or equal to 'a'
and less than or equal to 'z'
. Or, if you ask a user to respond with a y
or an n
, you want to accept uppercase (Y
and N
) as well as lowercase. To meet this kind of need, C++ provides three logical operators to combine or modify existing expressions. The operators are logical OR, written ||
; logical AND, written &&
; and logical NOT, written !
. Let’s examine them now.
3.139.83.199