Switch statement is used to execute a part of the code block based on the condition set. The condition can be checked by a series of case statements and if found TRUE then that particular set of code is executed. Here is the syntax for the a standard switch statement in C program.
switch( expression )
code block 1
Code block 2
Code block for default
Here the value of expression is check for matching with value given under case. If it matches then the code block in this case will be executed.
When the compiler executes break statement it comes out of the switch statement. So by keeping a break statement in our code block of a case comparison we will stop or end the code block. If we don't use a break statement then complier will execute all the balance statement till the end of the switch which will result in undesired result.
This is optional block of code gets executed if none of the case statements matches with expression or became true. Usually it is kept towards end after all the case statements are over ( within switch ).
Let us try switch statement with an example. We will ask to enter Grade from A to D and based on this input we will display a message saying the grade. If our entered character ( or grade ) does not match with any of the case statements then we will execute the default code with a message. Here is the code.
printf(" Please enter your Grade From A to D \n");
printf("You got A grade ");