The else if Statement

Sometimes a program needs to handle more than 2 possibilities (if, else). Therefore, we can add more conditions using the else if statement. For example in football, either the home team can win, or the visitors, or it's a draw:

int goalsHome = 3;
int goalsAway = 2;

if (goalsHome < goalsAway) {
    std::cout << "Away team won!" << std::endl;
} else if (goalsHome > goalsAway) {
    std::cout << "Home team won!" << std::endl;
} else {
    std::cout << "It's a draw!" << std::endl;
}

Here we can see 1 else if statement, but we can add as many as we want.

It's important to realize that conditions are evaluated from top to bottom. This means that the code block of the first condition that evaluates to true (true) will be executed. In the example above, goalsHome < goalsAway is false (false) and goalsHome > goalsAway is true, so the code block of the first else if statement is executed and the rest of the conditions are skipped. If no condition was true, the code block of the else statement would be executed.

Instructions

Use the else if statement that prints Just Do It if the brand is "Nike".

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

6/10

The else if Statement | Start Coder