Cs112 - Programming Fundamental: Lecture # 17 - Selection Control in C Syed Shahrooz Shamim
Cs112 - Programming Fundamental: Lecture # 17 - Selection Control in C Syed Shahrooz Shamim
Switch case statements are a substitute for long if statements that compare a
variable to several "integral" values ("integral" values are simply values that can be
expressed as an integer, such as the value of a char). The basic format for using
switch case is outlined below. The value of the variable given into switch is compared
to the value following each of the cases, and when one value matches the value of
the variable, the computer continues executing the program from that point.
Switch Case
SYNTAX
switch(variable||constant||character)
{
case 1:
statement1;
statement2;
break;
case 2:
statements;
break;
.
.
default:
statements;
}
Switch Case
• The condition of a switch statement is a value. The case says that if it
has the value of whatever is after that case then do whatever follows
the colon.
switch ( a ) {
case b:
/* Code */
break;
case c:
/* Code */
break;
default:
/* Code */
break;
}
Switch Case
• The default case is optional, but it is wise to include it as it
handles any unexpected cases. It can be useful to put some
kind of output to alert you to the code entering the default case
if you don't expect it to. Switch statements serve as a simple
way to write long if statements when the requirements are met.
Often it can be used to process input from a user.
Switch Case
Example.. default:
void main() printf(“I am in
{ default\n”);
char ch=‘x’; }
switch(ch) }
{
case ’v’:
printf(“In case v ”);
break;
case ’a’:
printf(“In case a ”);
break;
case ’x’:
printf(“In case x ”);
break;
Switch Case
• Switch statement can also contain Expressions
eg switch(i+j*k)
switch(45*j)