Follow

Subscribe

Follow

Subscribe

Switch case command: selection structure

Learn all the details of the switch case command. The command that allows you to create selection structures in computer programming.

The switch case command is an excellent feature of programming languages for creating selection structures. It works as a substitute for long conditional structures that use if-else expressions.

If you still don’t know what conditional structures are, read our article that explains in detail about this subject.

But let’s get down to business!

The structure of the switch case command

The switch case command is a tool to build conditional structures in a more elegant way.

Basically, it provides a mechanism for replacing nested if-else structures with a cleaner structure.

The code below illustrates the basic structure of the switch case command:

1.switch(variable){

2.case value1:

3.     //commands executed if "variable" == value1 

4.     break;

5.case value2:

6.     //commands executed if "variable" == value2  

7.     break;

8....

9.default:

10.     //commands executed if "variable" is different from all  

11.}

It consists of a variable (line 1 of the code above) whose value is tested by the case clauses (lines 2 and 5 of the code above). If the value of the variable is equal to any of the values of the case clause, the respective commands will be executed (lines 3 and 6 of the code above).

The default clause (line 9 of the code above) represents the exception. If the value of the variable is not equal to any value tested by the case clauses, the defualt clause commands are executed (line 10 of the code above).

The break command (lines 4 and 7 of the code above) is required after the commands in each case clause. It is used for the structure to be interrupted after the execution of any of the commands. This prevents further tests from being performed.

Understanding the switch case command

To understand how the switch case works, let’s imagine an algorithm that compares the value of a numeric variable and uses that value to print levels of difficulty.

Using if-else

The code below illustrates the implementation of this algorithm using the already known if-else commands:

1.if(level==1){

2.     println("Easy");

3.}else if(level==2){

4.     println("Moderate");

5.}else if(level==3){

6.     println("Hard");

7.}else{

8.     println("Error!");

9.}

Note in lines 1, 3, 5 and 7 (code above) that the conditional expressions filter the possible values of the “level” variable and print a specific message for each of these values.

The else command (line 7 of the code above) serves as an exception filter. If none of the previous alternatives were true, line 8 (code above) is executed.

Using switch case

Now let’s rewrite that same algorithm using the switch case selection structure:

1.switch(level){

2.case 1:

3.     println("Easy");

4.     break;

5.case 2:

6.     println("Moderate"); 

7.     break;

8.case 3:

9.     println("Hard");

10.     break;

11.default:

12.     println("Error!");

13.}

Did you notice the difference? Notice how the code is cleaner! Instead of using the expression “level==1“, we only use the word “case 1:“.

Note on lines 2, 5, and 8 (code above) how we don’t need to use the relational equality operator “==“. In the switch case command, the equality operator is already implied. We don’t need to write it.

However, it is important to note that not all programming languages will support this command. The Python language, for example, does not have the switch case command, and the if-else structure should be used instead.

See below the code above implemented in several different programming languages:

1.import java.util.Scanner;

2.class Main {

3.     public static void main(String[] args) {

4.          Scanner scanner = new Scanner(System.in);

5.          System.out.println("Enter the level, from 1 to 3:");

6.          int level=scanner.nextInt();

7.          switch(level){

8.          case 1:

9.               System.out.println("Easy");

10.               break;

11.          case 2:

12.               System.out.println("Moderate");

13.               break;

14.          case 3:

15.               System.out.println("Hard");

16.               break;

17.          default:

18.               System.out.println("Error!");

19.          }

20.     }

21.}

1.#include <stdio.h>

2.int main(void) {

3.     printf("Enter the level, from 1 to 3:\n");

4.     int level;

5.     scanf("%d",&level);

6.     switch(level){

7.     case 1:

8.          printf("Easy");

9.          break;

10.     case 2:

11.          printf("Moderate");

12.          break;

13.     case 3:

14.          printf("Hard");

15.          break;

16.     default:

17.          printf("Error!");

18.     }

19.}

1.#include <iostream>

2.int main() { 

3.     std::cout << "Enter the level, from 1 to 3:\n";

4.     int level;

5.     std::cin >> level;

6.     switch(level){

7.     case 1:

8.          std::cout << "Easy";

9.          break;

10.     case 2:

11.          std::cout <<"Moderate";

12.          break;

13.     case 3:

14.          std::cout <<"Hard";

15.          break;

16.     default:

17.          std::cout <<"Error!";

18.     }

19.}

1.using System;

2.class MainClass {

3.     public static void Main (string[] args) {

4.          Console.WriteLine("Enter the level, from 1 to 3:");

5.          int level=Convert.ToInt32(Console.ReadLine());

6.          switch(level){

7.          case 1:

8.               Console.WriteLine("Easy");

9.               break;

10.          case 2:

11.               Console.WriteLine("Moderate");

12.               break;

13.          case 3:

14.               Console.WriteLine("Hard");

15.               break;

16.          default:

17.               Console.WriteLine("Error!");

18.               break;

19.          }

20.     }

21.}

1.# Python lacks support for the switch/case command

2.# if-else structure should be used

3.level = int(input("Enter the level, from 1 to 3:\n"))

4.if level==1:

5.     print("Easy")

6.elif level==2:

7.     print("Moderate")

8.elif level==3:

9.     print("Hard")

10.else:

11.     print("Error!")

Limitation of the switch case command

We saw that a switch case selection structure implicitly uses the relational operator==” to perform the comparisons. The consequence of this is that if a conditional structure (which uses if-else) uses other relational operators, it cannot be transformed into a switch case!

To understand this better, look at the algorithm that classifies a student into categories, according to their age.

1.if(age < 12){

2.     println("Category: CHILD");

3.} else if(age < 16){

4.     println("Category: JUNIOR");

5.} else if(age < 20){

6.     println("Category: YOUNG");

7.} else {

8.     println("Category: ADULT");

9.}

We can see in lines 1, 3 and 5 (code above) that the operator less than<” is used to make the comparisons within the conditional expressions.

This means that the structure above cannot be transformed into a selection structure!

That is, if a structure is made up of conditional expressions that use relational operators other than “==“, such as “>“, “<“, “>=“, “<=” and “!=“, they cannot be converted to switch case selection structures!

Practices

Check out the practices we have prepared below to help you deepen your knowledge on this subject!

Choose your programming language and dig deeper.

Take the next step. Read our article about arrays. Get into the wonderful universe of programming data collections.

Was this article helpful to you?

So support us and share it with others who are interested in this subject!

WhatsApp
Facebook
Twitter
LinkedIn
Email

Other articles

Subscribe

This website uses cookies to ensure you get the best experience on our website.