We have been doing decision making by using if statement. The switch statement is also used for decision making.
To understand the switch statement, let’s consider a problem. We will first solve this problem by using if and then we will solve this problem by using switch statement. Let us consider a program that will input a number from 1-7 and then display the day of week that corresponds to the number. The correspondence is as follows:
Solution for this problem by using if
Now let’s see the syntax for switch statement:
*You can use as many case statements as you want
**It is not necessary to add the default statement
***If you do not add the break; statement, all the below statements will also be executed
Now let’s solve the above problem using switch:
*Try to remove break; to see what happens
- Write a program to input the month number and display the name of the month on the screen.