If…Then…ElseIf…Else

In some problems there are not just two different outcomes but more than two. If this is the case, then a simple If…Then…Else structure will not work. In these situations an If…Then…ElseIf…Else might be used. In this type of structure there can be more than just one Boolean condition and each is checked in sequence. Once a Boolean expression is met (the value is true), then the specified section of code for that Boolean expression is executed. Once executed, all other conditions are skipped over and the flow of logic goes right down to the bottom of the structure. It is important to remember that one and only one section of code can be executed. Even if several of the Boolean conditions happen to be met, the first and only the first one will be evaluated and run.

The structure can contain many ElseIfs, as many as the programmer needs. Another optional piece of the structure is the, “Else”. If none of the above Boolean conditions are met, the programmer might want a section of code to be executed that is a catch all. If this is the case, then the code is placed in the else section. Any code in the else section is run if and only if none of the Boolean expressions were met. It should also be noted that there is no Boolean condition associated with the else. That is because it is run only if all the above Boolean conditions are not met. The If…Then…ElseIf…Else statement (in most computer programming languages) takes the generic form of:

IF (Boolean expression #1) THEN
first potential statements to be performed
ELSEIF (Boolean expression #2) THEN
second potential statements to be performed
ELSEIF (Boolean expression #3) THEN
third potential statements to be performed
ELSEIF (Boolean expression #n) THEN
Nth potential statements to be performed
ELSE
alternate statements to be performed
ENDIF

When you approach a street light, there are not just 2 choices there are actually 3 (or maybe more). The following example will tell the driver (or the self-driving car), what to do as they approach a stop light. The driver will need to know what to do if the light is red, yellow or green. If the light is red, the driver needs to stop. If the light is yellow, the driver needs to slow down. If the light is green, the driver needs to go. If the light is not red, yellow or green, the driver needs to do something else. The following code shows how this might be done:

Top-Down Design for If…Then…ElseIf…Else statement

Top-Down Design for If…Then…ElseIf…Else statement

Flowchart for If…Then…ElseIf…Else statement

If…Then…ElseIf…Else flowchart

Pseudocode for If…Then…ElseIf…Else statement

GET light_color
IF (light_color == “red”) THEN
SHOW “Stop!”
ELSEIF (light_color == “yellow”) THEN
SHOW “Slow down!”
ELSEIF (light_color == “green”) THEN
SHOW “Go!”
ELSE
SHOW “Not sure!”
ENDIF

Code for If…Then…ElseIf…Else statement

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// Copyright (c) 2020 Mr. Coxall All rights reserved.
//
// Created by: Mr. Coxall
// Created on: Sep 2020
// This program checks a traffic light

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
    // this function checks a traffic light
    char lightColor[10];

    // input
    printf("Enter the color of the traffic light: ");
    scanf("%s", lightColor);

    // process and output
    if (strcmp(lightColor, "red") == 0) {
        printf("Stop!\n");
    } else if (strcmp(lightColor, "yellow") == 0) {
        printf("Slow down!\n");
    } else if (strcmp(lightColor, "green") == 0) {
        printf("Go!\n");
    } else {
        printf("Not a valid color.\n");
    }

    printf("\nDone.\n");
    return 0;
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// Copyright (c) 2020 Mr. Coxall All rights reserved.
//
// Created by: Mr. Coxall
// Created on: Sep 2020
// This program checks a traffic light

#include <iostream>
#include <string>

int main() {
    // this function checks a traffic light
    std::string lightColor;

    // input
    std::cout << "Enter the color of the traffic light: ";
    std::cin >> lightColor;

    // process and output
    if (lightColor == "red") {
        std::cout << "Stop!" << std::endl;
    } else if (lightColor == "yellow") {
        std::cout << "Slow down!" << std::endl;
    } else if (lightColor == "green") {
        std::cout << "Go!" << std::endl;
    } else {
        std::cout << "Not a valid color." << std::endl;
    }

    std::cout << std::endl
              << "Done." << std::endl;
    return 0;
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/* Created by: Mr. Coxall
 * Created on: Sep 2020
 * This program checks a traffic light
*/

using System;

/*
 * The Program class
*/
class Program {
    static void Main() {
        // this function checks a traffic light
        string lightColor;

        // input
        Console.Write("Enter the color of the traffic light: ");
        lightColor = Console.ReadLine();

        // process and output
        if (lightColor == "red") {
            Console.WriteLine("Stop!");
        } else if (lightColor == "yellow") {
            Console.WriteLine("Slow down!");
        } else if (lightColor == "green") {
            Console.WriteLine("Go!");
        } else {
            Console.WriteLine("Not a valid color.");
        }

        Console.WriteLine("\nDone.");
    }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/**
 * Created by: Mr. Coxall
 * Created on: Sep 2020
 * This program checks a traffic light
 */
//nolint:gocritic
package main

import "fmt"

func main() {
	// this function checks a traffic light
	var lightColor string

	// input
	fmt.Print("Enter the color of the traffic light: ")
	fmt.Scan(&lightColor)

	// process and output
	if lightColor == "red" {
		fmt.Println("Stop!")
	} else if lightColor == "yellow" {
		fmt.Println("Slow down!")
	} else if lightColor == "green" {
		fmt.Println("Go!")
	} else {
		fmt.Println("Not a valid color.")
	}

	fmt.Println("\nDone.")
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
/*
 * This program checks a traffic light
 *
 * @author  Mr Coxall
 * @version 1.0
 * @since   2020-09-01
 */

import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    // this function checks a traffic light
    String lightColor;

    // input
    Scanner scanner = new Scanner(System.in);
    System.out.print("Enter the color of the traffic light: ");
    lightColor = scanner.nextLine();

    // process and output
    if (lightColor.equals("red")) {
      System.out.println("Stop!");
    } else if (lightColor.equals("yellow")) {
      System.out.println("Slow down!");
    } else if (lightColor.equals("green")) {
      System.out.println("Go!");
    } else {
      System.out.println("Not a valid color.");
    }

    System.out.println("\nDone.");
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
/* Created by: Mr. Coxall
 * Created on: Sep 2020
 * This program checks a traffic light
*/

const prompt = require('prompt-sync')()

// input
const lightColor = prompt('Enter the color of the traffic light: ')

// process and output
if (lightColor === 'red') {
  console.log('Stop!')
} else if (lightColor === 'yellow') {
  console.log('Slow down!')
} else if (lightColor === 'green') {
  console.log('Go!')
} else {
  console.log('Not a valid color.')
}

console.log('\nDone.')
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#!/usr/bin/env python3
"""
Created by: Mr. Coxall
Created on: Sep 2020
This module checks a traffic light
"""


def main() -> None:
    """The main() function checks a traffic light, returns None."""

    # input
    light_color = input("Enter the color of the traffic light: ")

    # process and output
    if light_color == "red":
        print("Stop!")
    elif light_color == "yellow":
        print("Slow down!")
    elif light_color == "green":
        print("Go!")
    else:
        print("Not a valid color.")

    print("\nDone.")


if __name__ == "__main__":
    main()

Example Output

Code example output