C Switch Case: C Switch Case Syntax & Switch Case Example
C switch case is a multiple branch selection statement in which the value of an expression is checked against a list of integers or character constants. C switch case can be used to perform one of the several possible action depending of the evaluated value of a logical expression or character or integer constant.
C Switch Case Syntax
switch(expression)
{
case value_1: program statement;
program statement;
….
break;
case value_2:program statement;
…..
break;
case value_n:program statement;
…..
break;
default: program statement;
program statement;
……
break;
}
C Switch Case Working
C switch case works as follows. The expression is evaluated first which must either result into an integer or a character constant, and the values(value_1, value_2,…, value_n) must be either an integer or character constant.
After evaluation of expression, the evaluated value is matched against value_1, value_2,…, value_n and when an exact match is found the statements connected with that value are executed.
But, in case if no match is found, then, the statements connected with default are executed.
It should be noted that the use of both default and break statements are optional. And, the use of break statement in switch case brings the compiler out of the switch case.
C Switch Case Example
/* C menu driven program using switch case performing operations related to rectangle */ #include<stdio.h> #include<math.h> main() { int choice,l,b; printf("1. Calculate area of rectanglen"); printf("2. Calculate perimeter of rectanglen"); printf("3. Calculate diagonal of rectanglen"); printf("Please enter your choicen"); scanf("%d",&choice); printf("Please enter length of rectanglen"); scanf("%d",&l); printf("Please enter breadth of rectanglen"); scanf("%d",&b); switch(choice) { case 1: printf("Area of rectangle= %d", l*b); break; case 2: printf("Perimeter of rectangle= %d", 2*(l*b)); break; case 3: printf("Diagonal of rectangle= %d", sqrt(l*l+b*b)); break; default: printf("Invalid choicen"); } return 0; }