5.1 Coding a Switch Statement

A switch statement is used when you have multiple cases, or possibilities, that a certain variable can be. Having a switch statement is similar to having multiple if statements since they are both types of conditional structures, but the code is much more condensed and concise when using a switch statement. This structure is much better understood through an example, so let’s look at the one below:
int age = 3; switch(age) { case 1: printf(“Your age is 1”); break; case 2: printf(“Your age is 2”); break; case 3: printf(“Your age is 3”); break; case 4: printf(“Your age is 4”); break; case 5: printf(“Your age is 5”); break; default: printf(“You are older than 5”); break; }
In the above example, we have a variable named age of type int that is assigned a value of 3. Then, we have a switch statement that takes in the value of the variable age. Within the switch statement, there are multiple cases and each case checks to see if the value of age matches the number represented in each case. For example, the first case checks to see if the value of age matches the value of 1. Since the value of age does not equal 1, the computer skips over the first case. The computer will keep checking these cases until it finds one that matches. In our example, this would happen when the computer reaches case 3. After the computer checks to see that the value of age matches 3, it will execute everything that happens after the colon (:) until the break statement. This means that the code would output “Your age is 3”. Notice that after every case, there is a break statement. This break statement basically means that once the computer reads and executes the lines of code before the break statement, it will exit out of the switch statement completely and if there is any code after the switch statement, it will read and execute that. Let’s say, for instance, age is equal to 6 before the computer reads the switch statement. Notice how the switch statement only codes cases for numbers 1 through 5. In this situation, the computer would go to the default case, which will execute if none of the other cases match the value of the variable in question. In our example, the computer would then print “You are older than 5”.

Next Section

Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.