An if/else statement allows us to execute exactly one out of two blocks of code based on a condition. If the condition is true, the first block runs; if it's false, the second block runs.
But what if we want to choose between more than two options? For example, instead of just determining whether a score is passing or failing, we might want to give different messages for different ranges of scores. This is where else if comes in:
if (condition1) {
// This code runs when condition1 is true
}
else if (condition2) {
// This code runs when condition1 is false but condition2 is true
}
else {
// This code runs when both conditions are false
}The computer checks each condition in order until it finds one that's true, then runs that block and skips the rest.
Run the code and try different scores to see how the three different messages appear. Notice how scores of 80 or higher get a special "distinction" message.
Output (Console)