Select Case
As you have seen from the If…Elseif…Elseif…Else statement, when there are many choices, the structure can be hard to follow. Some programming languages have an alternative structure when this happens. The Select Case or Switch Case statement is also a decision structure that is sometimes preferred because code might be easier to read and understand, by people.
The Select Case structure takes a variable and then compares it to a list of expressions. The first expressions that is evaluated as, “True” is executed and the remaining of the select case structure is skipped over, just like an If…ElseIf… statement (but not in all languages!). There are several different ways to create your expression. You can just use a value (a single digit for example and then it does an equal comparison), several digits, a range or having a regular expression. Just like the If structure, there is an optional “Else” that can be placed at the end as a catch all. The general form of a Select…Case statement (in most computer programming languages), takes the generic form of:
SELECT (variable)
CASE valueOne
CASE valueTwo
CASE valueThree
…
ELSE //optional
In this example program, the user enters in a grade letter. The letter grades are A, B, C, D & F. The computer will tell you if you are doing well, average or poorly. If the user enters in a grade that is not A, B, C, D or F, the computer will tell you that you have entered in an invalid grade.
Top-Down Design for Select Case statement
Flowchart for Select Case statement
Pseudocode for Select Case statement
GET grade
SELECT (grade)
CASE “A”
CASE “B”
CASE “C”
CASE “D”
CASE “F”
ELSE
Code for Select Case 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
33
34
35
36
37
38
39
40
41
42
43 | // Copyright (c) 2020 Mr. Coxall All rights reserved.
//
// Created by: Mr. Coxall
// Created on: Sep 2020
// This program checks your grade
#include <stdio.h>
#include <ctype.h>
int main() {
// this function checks your grade
char gradeLevel; // a single character
// input
printf("Enter grade mark as a single character(ex: A, B, ...): ");
scanf("%c", &gradeLevel);
// process and output
// Note you need the break in C or it will move to next
// line in switch statement if it is true again
switch (toupper(gradeLevel)) {
case 'A':
printf("Excellent!\n");
break;
case 'B':
printf("Good job!\n");
break;
case 'C':
printf("Average.\n");
break;
case 'D':
printf("Poor.\n");
break;
case 'F':
printf("Fail.\n");
break;
default:
printf("Invalid grade.\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
33
34
35
36
37
38
39
40
41
42
43 | // Copyright (c) 2020 St. Mother Teresa HS All rights reserved.
//
// Created by: Mr. Coxall
// Created on: Sep 2020
// This program checks your grade
#include <iostream>
#include <cctype>
int main() {
// this function checks your grade
char gradeLevel; // a single character
// input
std::cout << "Enter grade mark as a single character(ex: A, B, ...): ";
std::cin >> gradeLevel;
// process and output
// switch in C++ can not support strings, only numbers and char
// also note you need the break in C++ or it will move to next
// line in switch statement if it is true again
switch (toupper(gradeLevel)) {
case 'A':
std::cout << "Excellent!" << std::endl;
break;
case 'B':
std::cout << "Good job!" << std::endl;
break;
case 'C':
std::cout << "Average." << std::endl;
break;
case 'D':
std::cout << "Poor." << std::endl;
break;
case 'F':
std::cout << "Fail." << std::endl;
break;
default:
std::cout << "Invalid grade." << std::endl;
}
std::cout << "\nDone." << std::endl;
}
|
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
35
36
37
38
39
40
41
42
43 | /* Created by: Mr. Coxall
* Created on: Sep 2020
* This program checks a student's grade
*/
using System;
/*
* The Program class
*/
class Program {
static void Main() {
// this function checks a student's grade
// create Scanner object for user input
Console.Write("Enter your grade: ");
string grade = Console.ReadLine();
// process & output
switch (grade.ToUpper()) {
case "A":
Console.WriteLine("Excellent!");
break;
case "B":
Console.WriteLine("Good job!");
break;
case "C":
Console.WriteLine("Average.");
break;
case "D":
Console.WriteLine("Poor.");
break;
case "F":
Console.WriteLine("Fail.");
break;
default:
Console.WriteLine("Invalid grade.");
break;
}
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
32
33
34
35
36
37
38
39
40 | /**
* Created by: Mr. Coxall
* Created on: Sep 2020
* This program checks a student's grade
*/
package main
import (
"fmt"
"strings"
)
func main() {
// this function checks a student's grade
var grade string
// input
fmt.Print("Enter your grade: ")
fmt.Scanln(&grade)
// process and output
switch strings.ToUpper(grade) {
case "A":
fmt.Println("Excellent!")
case "B":
fmt.Println("Good job!")
case "C":
fmt.Println("Average.")
case "D":
fmt.Println("Poor.")
case "F":
fmt.Println("Fail.")
default:
fmt.Println("Invalid grade.")
}
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48 | /*
* This program checks a student's grade
*
* @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
// create Scanner object for user input
Scanner scanner = new Scanner(System.in);
// input
System.out.print("Enter your grade: ");
String grade = scanner.nextLine();
// process & output
switch (grade.toUpperCase()) {
case "A":
System.out.println("Excellent!");
break;
case "B":
System.out.println("Good job!");
break;
case "C":
System.out.println("Average.");
break;
case "D":
System.out.println("Poor.");
break;
case "F":
System.out.println("Fail.");
break;
default:
System.out.println("Invalid grade.");
break;
}
// close the Scanner object
scanner.close();
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
23
24
25
26
27
28
29
30
31
32
33 | /* Created by: Mr. Coxall
* Created on: Sep 2020
* This program checks a student's grade
*/
const prompt = require("prompt-sync")()
// input
const grade = prompt("Enter your grade: ")
// process & output
switch (grade.toUpperCase()) {
case "A":
console.log("Excellent!")
break
case "B":
console.log("Good job!")
break
case "C":
console.log("Average.")
break
case "D":
console.log("Poor.")
break
case "F":
console.log("Fail.")
break
default:
console.log("Invalid grade.")
break
}
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
30
31
32
33
34
35 | #!/usr/bin/env python3
"""
Created by: Mr. Coxall
Created on: Sep 2020
This module checks a student's grade
"""
def main() -> None:
"""The main() function checks a student's grade, returns None."""
# input
grade = input("Enter grade mark as a single character(ex: A, B, ...): ")
# process & output
# NOTE: This will only work on >= Python 3.10
match grade.upper():
case "A":
print("Excellent!")
case "B":
print("Good job!")
case "C":
print("Average.")
case "D":
print("Poor.")
case "F":
print("Fail.")
case _:
print("Invalid grade.")
print("\nDone.")
if __name__ == "__main__":
main()
|
Example Output