Switch case statement is used to control the flow of the compiler in a program. Switch case works on "Cases" i.e, it will compare the given expression to the cases written in the program.
Syntax:- switch(expression){
case 1:
Statement 1;
break;
case 2:
Statement 2;
break;
default:
Statement 3;
}
In the case we can also use characters like alphabets and special symbols but they should be written inside single coats( ' ' ).
for eg:
case 'a':
Statement 1;
OR
case '#':
Statement a;
WORKING CONCEPT:-
Example 1 |
- First compiler will going to check whether the value of 'a'(expression) is similar to any case constant( like in "Case 1" 1 is case constant) or not.
- If the value of 'a'(expression) is similar to any of the case constant then it will execute only that block which belongs to that case. for eg: If the value of 'a' is 1 then it will only print "Good".
- If no case constant matches with the value of 'a' then "default" is going to execute.
Things To Remember
- The datatype of "Expression" can be integer, character but it can't be of double datatype.
- There should not be two similar cases. for eg:
case 1:
Statement a;
case 1:
Statement b; - switch, case, default keywords are in lower case( in small letters).
- Do not use braces in the case. for eg:
Example 2
Here after the cases braces were used which is incorrect. - If the break statement is not written then all the other cases below that Case(similar to expression) will be executed unit and unless it founds break statement. for eg:
Example 3 - We can write cases in any order i.e, We can write default and case constant anywhere inside the Switch_Case.
For giving some suggestion please check our "Contact us" page. Also more update related to coding will be added in this Blog later on, so please get attached with this Blog. Thank you for your support and time...
2 Comments
Thanks Nikhilesh really I don't know the concept behind switch case statements in C programming,thank you so much my dear friend.
ReplyDeleteIts my pleasure friend. Hope you will get more help with the upcoming Post.
Delete