< Previous | Contents | Next >
Introducing the Score Rater 3.0
The Score Rater 3.0 program also rates a score, which the user enters. But this time, the program uses a sequence of if statements with else clauses. Figure 2.4 shows the results of the program.
Figure 2.4
The user can get one of multiple messages, depending on his score.
You can download the code for this program from the Course Technology website (www.courseptr.com/downloads). The program is in the Chapter 2 folder; the filename is score_rater3.cpp.
// Score Rater 3.0
// Demonstrates if else-if else suite
#include <iostream> using namespace std;
int main()
{
int score;
cout << "Enter your score: "; cin >> score;
50 Chapter 2 n Truth, Branching, and the Game Loop: Guess My Number
if (score >= 1000)
{
cout << "You scored 1000 or more. Impressive!\n";
}
else if (score >= 500)
{
cout << "You scored 500 or more. Nice.\n";
}
else if (score >= 250)
{
cout << "You scored 250 or more. Decent.\n";
}
else
{
cout << "You scored less than 250. Nothing to brag about.\n";
}
return 0;
}
Creating a Sequence of if Statements with else Clauses You’ve seen the first part of this sequence twice already, and it works just the same this time around. If score is greater than or equal to 1000, the message,
“You scored 1000 or more. Impressive!” is displayed and the computer branches
to the return statement.
if (score >= 1000)
However, if the expression is false, then we know that score is less than 1000 and the computer evaluates the next expression in the sequence:
else if (score >= 500)
If score is greater than or equal to 500, the message, “You scored 500 or more. Nice.” is displayed and the computer branches to the return statement. However, if that expression is false, then we know that score is less than 500 and the computer evaluates the next expression in the sequence:
else if (score >= 250)
If score is greater than or equal to 250, the message, “You scored 250 or more. Decent.” is displayed and the computer branches to the return statement.
Using the switch Statement 51
However, if that expression is false, then we know that score is less than 250 and the statement associated with the final else clause is executed and the message, “You scored less than 250. Nothing to brag about.” is displayed.
Hin t
While the final else clause in an if else-if suite isn’t required, you can use it as a way to execute code if none of the expressions in the sequence are true.