Switch Case in C

05 min read

Switch Statement: If one of the several available alternatives has to be selected, switch-case can be used.

Syntax:

switch(expression)
{
case  value-1:
statement block-1;
break;
case value-2:
statement block-2;
break;
.......
case value-n:
statement block-n;
break;
default:
default statement block;
}


The expression should result in a character constant or integer constant. If the value of the expression matches with any of the case values, the statement specified in that case is executed. The 'break' statement is used to immediately make the control come out of the structure in which it is specified. Thus if one case value is matching with the expression value, the corresponding statement is executed and then the control is transferred out of the switch structure, without moving to the remaining case labels. If none of the case value matches with the expression value, the default case will be executed. 'default' case is optional.

Example: To print the name of the day, if the day number is inputted.

int main( )
{
int dayno;
printf("Enter the day number:");
scanf("%d",&dayno);
switch(dayno)
{
case 1: printf("Sunday\n");
break;
case 2: printf("Monday\n");
break;
case 3: printf("Tuesday\n");
break;
case 4: printf("Wednesday\n");
break;
case 5: printf("Thurday\n");
break;
case 6: printf("Friday\n");
break;
case 7: printf("Saturday\n");
break;
default: printf("Enter a valid day number\n");
}
getch( );
return 0;
}

 

If day number is 5, the output will be 'Thursday'. Since there is a break statement next to that printf statement, the control is transferred to outside the switch structure. Thus other remaining cases will be simply ignored. 'default' case is optional. If needed, it can be specified. If the input value does not match with any of the 7 case values, default case will be executed. For example, if dayno=l0, it does not match with any of the case values and so output will be 'Enter a valid day number'.

 

The significance of 'break' statement: If 'break' is not mentioned after every case, once a case value matches, the corresponding statement will be executed and the control flows down through the remaining cases also ie., all the remaining statements in switch block will also be executed.

Example:

switch(dayno)
{
case 1: printf("Sunday\n");
case 2: printf("Monday\n");
case 3: printf("Tuesday\n");
case 4: printf("Wednesday\n");
case 5: printf("Thurday\n");
case 6: printf("Friday\n");
case 7: printf("Saturday\n");
default: printf("Enter a valid day number\n");
}

 

If dayno=4, the output will be

Wednesday
Thursday
Friday
Saturday
Enter a valid day number
POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error