Computer Concept & Programming In C - Unit III - 5

Q.7 What is switch structure? Make a program by using switch structure.
Related Questions -
Q. What is the role of SWITCH statement in C programming language? Give the syntax of SWITCH statement with a suitable example.                                                 (AKTU. 2010-11)
Q. Illustrate the use of break statment in C with some example.              (AKTU. 2013-14)
Ans. The switch construct: -
Instead of using the if-else-if ladder, the switch structure is ready to handle multiple choices, such as menu options. The general form of the switch structure is:
switch (variable)
{
case constant 1:
statement(s)
break;
case constant 2;
statement (s);
break;
case constant 3;
statement(s);
break;
……
default:
stamtent(s);
}
The switch structure starts with the switch keyboard followed by one block, which contains the different cases. Each case handles the statement corresponding to an option (a satisfied condition) and ends with the break statement, which transfer the control out of the switch structure to the original program. The variable between the parenthesis following the switch keyword is used to test the conditions and is referred to as the control variable. If it is evaluated as “constant 1” the case “constant 1” is executed. If evaluated as “constant 2” the “case constant 2” is executed and so forth. If the value of the variable does not correspond to any case the default case is executed. The control variable of the switch could be of the type int, long, or char.
Other types are not allowed.
# include <stdio.h>
# include <conio.h>
# include <stdlib.h>
void main ( )
{
int day;
clrscr ( );
printf (“\n Enter a single digit for a day”);
printf (“\n Within the range of 1 to 7”); 
day = getchar ( );
switch (day)
{
case ‘1’: printf (“\ n Day 1 is Sunday”);
break;
case ‘2’: printf (“\ n Day 2 is Monday”);
break;
case ‘3’: printf (“\ n Day 3 is Tuesday”);
break;
case ‘4’: printf (“\ n Day 4 is Wednesday”);
break;
case ‘5’: printf (“\ n Day 5 is Thursday”);
break;
case ‘6’: printf (“\ n Day 6 is Friday”);
break;
case ‘7’: printf (“\ n Day 7 is Saturday”);
break;
default: printf (“\ n The digit is out of range 1 to 7”);
break;
}
getch ( );
}
The output of the program is:
1. Enter a single digit for day
Within the range of 1 to 7: 3
Day 3 is Tuesday.
2. Enter a single digit for day
Within the range of 1 to 7: 9
The digit is out of range 1 to 7.