Using of Switch Case in C

In this, we are only talking about switch case for C Programming Language.

 

What is switch statement in C ??

Let's try to understand with the help of Syntax 

 switch(Expression)

{

case Constant_Expression1:

Statement(S1);

case Constant Expression2:

Statement(S2);

//We can have any of case statements //

.

.

.

default : Statement(S3)   //You Can think it is Just like else statement if the above condition are not satisfied then this will print default statement//

}

 

There is some Problem in above syntax have you notice that ??

No ! Don't worry I'll tell you 

In the above statement if one of the cases is satisfied then compiler don't check other cases it will directly print all the statements.

So, to prevent this we use to break after every case.

To make the things more clear....Let's try one example.

 

Q: Write a program to check the user input, belongs to which month?If the user gives the value greater than 12 then print a message  "Invalid Month !"   

Let's try to solve -

//I am direct writing the Logic, not including the header file//

{

int m;

printf("Enter the month");

scanf("%d",&m);

Switch(m)

{

case 1 : 

Printf("January");

case 2 :

Printf("Feb');

case 3 :

Printf("March");

case 4 :

Printf("Aprail");

case 5 :

Printf("May");

case 6 : 

Printf("June");

case 7 :

Printf("July");

case 8 :

Printf("August");

case 9 :

Printf("September");

case 10 :

Printf("October");

case 11 :

Printf("November");

case 12 :

Printf("December");

default :

Printf("Invalid month");

}

Here, if user gives :  8

then O/P will be :  "August" "September" "October" "November" "December"

Why ?? because we not write break after every case that why we get this problem. To resolve this use break; after every case .

if user gives : 13

Invalid Month

Program when we use Use break;  

{

int m;

printf("Enter the month");

scanf("%d",&m);

switch(m)

{

case 1 : 

Printf("January");

break;

case 2 :

Printf("Feb');

break;

case 3 :

Printf("March");

break;

case 4 :

Printf("Aprail");

break;

case 5 :

Printf("May");

break;

case 6 : 

Printf("June");

break;

case 7 :

Printf("July");

break;

case 8 :

Printf("August");

break;

case 9 :

Printf("September");

break;

case 10 :

Printf("October");

break;

case 11 :

Printf("November");

break;

case 12 :

Printf("December");

break;

default :

Printf("Invalid month");

}

User gives:  8

O/P  will be : "August"

 

 

 

 

This is all about Switch case.

I hope you like it :) !!

Any mistakes found please ping me or do comments ...thanks 

 

Contributor's Info

Created: Edited:
0Comment