In one of earlier post we introduced to decision making statements in c.Today we shall learn about one of the decision making statement in C “switch statement“.The switch statement allows you for checking a equality among the options available and then perform actions according to it.For checking the equality we use the keyword case.After executing the statements related to the choice we need to break it or else it will executed continuously without any break.
Syntax:
swtich(value) { case val1: statements for execution break; case val2: statements for execution break; . . . . default: statements for execution exit(); }
Each switch may or may not contain a default statement.If the given value doesn’t matches to any of the case value then the default statement’s execution will be done.A simple program to display the execution of switch statement and to display the name of the day with input as number.
#include<stdio.h> #include<conio.h> void main() { int n; clrscr(); printf("Enter a number in the range of 1-7 to show the corresponding day of the week:"); scanf("%d",&n); switch(n) { case 1:printf("\n\tFirst day of the week is Monday"); break; case 2:printf("\n\tSecond day of the week is Tuesday"); break; case 3:printf("\n\tThird day of the week is Wednesday"); break; case 4:printf("\n\tFourth day of the week is Thursday"); break; case 5:printf("\n\tFifth day of the week is Friday"); break; case 6:printf("\n\tSixth day of the week is Saturday"); break; case 7:printf("\n\tSeventh day of the week is Sunday"); break; } getch(); }
Output:
Download the source code