Reputation:
I'm reviewing for an exam and although we have an answer key, I don't understand the correct answer.
if (score >= 90)
grade = 'A';
if (score >= 80)
grade = 'B';
if (score >= 70)
grade = 'C';
if (score >= 60)
grade = 'D';
else
grade = ‘F’;
The answer key says that "This code will work correctly only if grade < 70". I know the else statement is linked with the last if-statement, but I'm still confused. Thanks for the help in advance.
Upvotes: 0
Views: 6315
Reputation: 40315
The snippet you've posted is 4 independent, unrelated if
statements, and the last one happens to have an else
condition. Since the statements are all separate, if one of the conditions is true, that doesn't prevent the other if statements from executing as well.
In your snippet, if score was e.g. 95, then grade would be set to 'A', then overwritten by 'B', then by 'C', then by 'D' and would ultimately end up as 'D'. However, if the score was < 70, the results left over from the final if
statement would coincide with the correct results, hence it only leaves grade
with the correct results when score < 70
.
The correct form would be:
if (score >= 90) grade = 'A';
else if (score >= 80) grade = 'B';
else if (score >= 70) grade = 'C';
else if (score >= 60) grade = 'D';
else grade = 'F';
If you try your code in a debugger with various inputs, and break on the first line, you can see exactly what is going on.
For more information, see the official tutorial on if-else
statements.
Upvotes: 3
Reputation: 1101
That is correct. If the score is greater than 70, then the grade will be the last statement to run, so the last thing grade
will be set to will always be 'D'. Thus, you need else if statements, or another technique, such as reversing all the if statements (ie putting if score>= 90
last).
Upvotes: 0