- When multiple decisions involved in the program at that time we can use else…if ladder but some time it is difficult to read and understand.
- In addition to this when the numbers of alternative are more than the complexity of the program will also get increase.
- In such situation C-Language provides another multi-way decision making statement called switch statement.
- The structure of switch statement is more standard and readable then the else if ladder.
- Switch statement uses different cases to be matched
- It will match the expression value with different cases available in switch statement from the top to down ward.
- Each case has its associated block of statement.
- Matching of the case value will perform from the first case. As soon as it founds the matching case, statements associated with that case block is executed and remaining cases are skipped.
- If no matching case is found then the default block will be executed if present.
- The default is optional if present then it will be executed otherwise no action will be taken.
- The following are the rules for the switch statement:
Rules for Switch statement:
- Switch expression must be of type integer or character.
- Each case value must be unique that means no two case value should be same.
- Default is optional it can be place anywhere in switch statement but normally it is place at the end.
- Break statement is also optional if not present then similar cases will be executed.
- It has the following form:
- Matching of case expression will be start from top to the down when it found matching case the block associated with that case expression executes then after control transfers to the statement-x.
- If case expression doesn’t match next case expression will be tested in sequential manner up to the last case and if no matching case is found, default block will be executed if present.
- the following program demonstrates the use of switch statement:
/* Program to demonstrate the use of switch statement for basic calculation
float x, y, ans;
printf("\nEnter your choice :");
printf("\nEnter X and Y :");
scanf("%f %f", &x, &y);
ans = x + y;
ans = x - y;
ans = x * y;
ans = x / y;
printf("\n Invalid choice! Please try again!");
printf("\n Answer is %.2f", ans);