Another way of controlling the flow switch of case
Welcome to the Newbie Programmer Series. In the last post (click here) we have learned how to use break and continue. We have learned how to use them as an alternative to the goto (click here). In this post we will learn about the switch statement. This is made for decision making and is easy alternative for if..else (click here). So if you are new to this series, please go to index (click here) and read out all the previous parts so that you can easily understand what is going down below.
Well you are thinking correct that we could have used if else here. But sometimes when the program have too many conditions and many nested if else etc the problem becomes too much complex. And the brackets { } makes it even worse. So in that case to make it simple, we use switch. Also if there are not so much logic operating then instead of using == again and again, switch makes it no need. Its easy and better option for making decisions based on variable values only.
Lets come to the coding stuffs.
The switch block look like this :
switch ( variable )
{
case const-1 :
//instructions
break;
case const-2 :
//instructions
break;
...
default :
//instructions
}
Note that there is no need of break; in default as it’s the last case so the program will automatically come out of the block even if it’s not there.
Look at the following piece of code.
#include<stdio.h>
main()
{
int like;
printf("What do you like the most ? \n");
printf("Enter your choice from 1 to 3 \n");
printf("(1) Video Games \n");
printf("(2) Music \n");
printf("(3) Manga \n");
printf("Enter Your Choice : ");
scanf("%d", &like);
switch(like)
{
case 1:
printf("I love Super Mario. \n");
break;
case 2:
printf("Michael Jackson is my favorite singer. \n");
break;
case 3:
printf("Dragon Ball is the best. \n");
break;
default :
printf("Bye because you entered wrong choice ! \n");
}
}
OUTPUT:
What do you like the most ?
Enter your choice from 1 to 3
(1) Video Games
(2) Music
(3) Manga
Enter Your Choice : 3
Dragon Ball is the Best .
second try:
What do you like the most ?
Enter your choice from 1 to 3
(1) Video Games
(2) Music
(3) Manga
Enter Your Choice : 7
Bye because you entered wrong choice !
What is happening here is that I have used the variable like as a switch. With different values of like, different instructions are to be followed. Using scanf user will enter a choice which is saved in like variable. Then I applied the switch block as shown above. When the user enters something which is not one of the cases, like if I enter 5 instead of 1 or 2 or 3 here, the default case will be executed.
So that’s it for today. In the next post, we are doing another interesting stuff. So stay connected.
Previous Chapter: « break and continue the loops
© Shubham Ramdeo, 2015-2025.
All Rights Reserved.