![]() |
Suppose you wanted to write a selection structure to assign a student a level based on their percentage. Can you spot the problem with the following block of code? How could you rewrite it so it will work properly? |
|---|
![]() |
The problem with the selection structure is that due to the order that the statements are written in, the second, third and fourth conditional will never be evaluated. Any mark greater than 50 (including marks greater than 60, 70 or 80) will be assigned a "Level 1". A possible way to rewrite it would be:
if (mark > 80) {
grade = "Level 4";
} else if (mark > 70) {
grade = "Level 3";
} else if (mark > 60) {
grade = "Level 2";
} else if (mark > 50) {
grade = "Level 1";
} else {
grade = "Below Level 1";
}
|
|---|