Limited access

Upgrade to access all content for this subject

Consider a relatively common situation in which you must compare a variable against several possible values and perform a different action based on the result of the comparisons. This situation can be implemented using a series of if-else conditionals. For example, consider the following code which chooses the appropriate workout for each day of the week:

if(day == "Monday") {
    pushups();
} else if(day == "Tuesday" || day == "Thursday") {
    crunches();
} else if(day == "Wednesday") {
    jogging();
} else if(day == "Friday") {
    lifting();
} else {
    relax();
}

This situation can be simplified using a switch statement. A switch statement takes a variable as input, and allows the programmer to specify different cases which execute different pieces of code.

Which of the following switch statements is equivalent to the code provided above?

A
switch(day) {
    case "Monday":
        pushups();
        break;
    case "Tuesday":
        crunches();
        break;
    case "Wednesday":
        jogging();
        break;
    case "Thursday":
        crunches();
        break;
    case "Friday":
        lifting();
        break;
}

relax();
B
switch(day) {
    case "Monday":
        pushups();
        break;
    case "Tuesday":
    case "Thursday":
        crunches();
        break;
    case "Wednesday":
        jogging();
        break;
    case "Friday":
        lifting();
        break;
    default:
        relax();
        break;
}
C
switch(day) {
    case "Monday":
        pushups();
    case "Tuesday":
        crunches();
    case "Wednesday":
        jogging();
    case "Thursday":
        crunches();
    case "Friday":
        lifting();
    default:
        relax();
}
D
switch(day) {
    case "Monday":
        pushups();
        break;
    case "Tuesday":
    case "Thursday":
        crunches();
    case "Wednesday":
        jogging();
        break;
    case "Friday":
        lifting();
        break;
    default:
        relax();
        break();
}
Select an assignment template