Chapter-7 Switch Case Control
Chapter-7 Switch Case Control
Chapter-7
Switch Case Control
Switch case
We studied earlier in decision control that how and when to use if, if-else.
They are good enough to select one from the two available options. When choices are
two, we can use if-else. Even if we have multiple choices we can use multiple if-else,
sometimes we use if-else ladder or nested if-else. You probably experienced that as the
number of available options/choices are large, if-else becomes complex.
So when we have many choices, we can use switch case control in place of if-else.
In this section we are going to use three key switch, case and default.
Syntax of switch case
main()
{
.
.
switch( expression)
{
case constant1 :
.
case constant2 :
.
case constant3 :
.
default:
}
..
}
Switch case control is used when user have multiple choices. Switch transfers the control
to a case written in its body depending on the value evaluated by expression in switch
parenthesis. In switch body each case is post fixed by a constant. This constant could be
integer or character but not real. It is also worth mentioning here that the constant in each
case must be distinct.
When value of expression does not match with any case constant then control moves on
default segment.
Another important point to notice that once control moves from switch to appropriate
case, it not just execute statement written in that case but also execute all the statements
goto control
The goto statement is used for unconditional jump from one part of the program to
another part of the program. It is always suggested not to use goto statement as this
reduces the readability of the program. Using goto statement is considered as poor
programming approach
Example
main()
{
.
int cm;
printf(Enter length in centimeters);
scanf(%d,&cm);
if(cm<100)
goto label;
cm=cm%100;
printf(Wrong input is trimed);
label:
printf(cm=%d, cm);