switch statement in C | Working of switch statement in C

Preview
You must first complete Simple if statement in C language before viewing this Lesson

 Switch statement in C

It is a selection statement that works with an expression or variable. It compares the value of expression or variable with values called cases of switch statement.

It value of expression or variable matches with any case value, statements linked with that case gets executed. This Expression or variable can be of integer or character data type.

Syntax:

switch(Exp)
{
case val1:
                        Block1;
case val2:
                        Block2;
case val3:
                        Block3;
:
:
default:
                        BlockN;    
}
switch keyword specifies he beginning of  switch statement.

Exp refers to character or integer variable or expression.

case  keyword specifies case within the switch block.

val1,val2,val3 are case values that get compared with expression or variable taken within parenthesis after switch statement. These can be only constant values.

If the value of expression is equal to value, Block1 will execute.  Block2 will execute, if the value of expression matches with value2, Block3 gets executed If expression matches with val3, and so on. default case will execute if expression doesn’t match with any case value. 

Block1, Block2, Block3,…. BlockN are validd statements of C language. 

break is a jumping statement to jump out of switch statement.



Program
#include<stdio.h>
int main()
{
int m;
printf(“\nEnter  value between 1 and 12:-“);
scanf(“%d”,&m);switch(m)
{case 1:
printf(“January”);
break;case 2:
printf(“February”);
break;case 3:
printf(“March”);
break;case 4:
printf(“April”);
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(“Wrong choice”);
break;
}
return(0);
}

Output
Enter a value between 1 and 12:-7
July
Description
In the above program, m has been entered 7.

As value of m matches with case 7:

So the statement printf(“July”) would be executed.



 

Best Books of Computer Science





 

Lesson tags: conditional statement in c, difference between if and switch, selection statement in c, switch statement in c, switch statement of c
Back to: C Programming Language