Multiway if-else-Statement

  1. The syntax of the multi-way if-else-statement is:

    if (Boolean_Expression_1)
        Statement_1
    else if (Boolean_Expression_2)
        Statement_2
    .
    .
    .
    else if (Boolean_Expression_n)
        Statement_n
    else
        Statement_for_all_other_possibilities

    The Boolean expression are checked one after the other until the first true Boolean expression is encountered, then the corresponding statement is executed. Program control is then passed to the statement after the multiway if-else-statement. If none of the Boolean expression is true then the statement after the last else is executed.

  2. The else and the statement associated with it are optional (not required to use them).

  3. There can be any number (including zero) of if-else blocks.

  4. Again any statement can be replaced by a compound statement or a block of statements.

  5. For example, consider writing a computerized number guessing game in which the program picks a random number between 1 and 10, and the player has 3 chances to take a guess at the number. Each time the player's guess is higher than the answer, the program will respond "too high", and if the number is lower than the answer, the program will respond with "too low", and if the guess is the same as the answer, the program responds with "correct!".

    Suppose the player's choice is stored in the variable guess, and the correct number is stored in the variable answer. You could code that as follows:

    if (guess > answer)
        cout << "Too high!\n";
    if (guess < answer)
        cout << "Too low!\n";
    if (guess == answer)
        cout << "Correct! You've just won a million dollars!\n";

    The code will do the job, but in an inefficient way. There are three separate if statements involving three separate conditions that must always be tested.

    A better way is to use a multiway if-else-statement to write:

    if (guess > answer)
        cout << "Too high!\n";
    else if (guess < answer)
        cout << "Too low!\n";
    else
        cout << "Correct! You've just won a million dollars!\n";

    Note that not all of the three conditions need to be tested. Since the three choices are mutually exclusive (i.e. one and only one of the conditions can be true), the last condition never needs to be tested.

  6. For better efficiency, try to arrange the cases so that the most probably ones are tested first. For example if the median score on the first exam is 52, meaning that half of the student has a score higher than 52 and the other half has a score lower than 52, but the average score to pass the course is fixed at 70, then it is better to write:

    if (score < 60)
        cout << "You need to do better the next exam!\n";
    else if (score < 75)
        cout << "You are barely passing so far.\n";
    else if (score < 90)
        cout << "You are doing well so far.\n";
    else
        cout << "Excellent work! Keep it up!\n";