Lesson 8
Lesson 8
LESSON NO 08
SWITCH STATEMENT
SWITCH STATEMENT
Sometimes, we have multiple conditions and take some action according to each condition. For example, in the
payroll of a company, there are many conditions to deduct tax from the salary of an employee. If the salary is less than
Rs. 10000, there is no deduction. But if it falls in the slab Rs. 10000 - 20000, then the income tax is deducted. If it
exceeds the limit of Rs. 20000, some additional tax will be deducted. So the appropriate deduction is made according
to the category or slab of the salary.
We can also understand this from the example of grades secured by the students of a class. Suppose we want to
print description of the grade of a student. If the student has grade ‘A’ we print ‘Excellent’ and 'Very good', 'Good',
'Poor' and 'Fail' for grades B, C, D, and F respectively. Now we have to see how this multi-condition situation can be
applied in a program. We have a tool for decision making i.e. 'if statement'. We can use 'if statement' to decide what
description for a grade should be displayed. So we check the grade in if statement and display the appropriate
description. We have five categories of grades-- A, B, C, D, and F. We have to write five if statements to check all the
five possibilities (probabilities) of grade. So we write this in our program as under-
if ( grade == ‘A’ )
cout << “Excellent” ;
if ( grade == ‘B’ )
cout << “Very Good” ;
if ( grade == ‘C’ )
cout << “Good” ;
if ( grade == ‘D’ )
cout << “Poor” ;
if ( grade == ‘F’ )
cout << “Fail” ;
These statements are correct and perform the required task. But the 'if statement' is computationally one of the
most expensive statements in a program. We call it expensive due to the fact that the processor has to go through
many cycles to execute an if statement to evaluate a single decision. So to make a program more efficient, try to use
the minimum number of if statements. This will make the performance of the program better.
So if we have different conditions in which only one will be true as seen in the example of student’s grades, the
use of if statement is very expensive. To avoid this expensiveness, an alternate of multiple if statements can be used
that is if/else statements. We can write an if statement in the body of an if statement which is known as nested if.
We can write the previous code of if statements in the following nested if/else form.
If ( grade == ‘A’ )
cout << “Excellent” ;
else if ( grade == ‘B’ )
cout << “Very Good” ;
else if ( grade == ‘C’ )
cout << “Good” ;
else if ( grade == ‘D’ )
cout << “Poor” ;
else if ( grade == ‘F’ )
cout << “Fail” ;
In the code, there is single statement with each if statement. If there are more statements with an if statement,
then don’t forget the use of braces and make sure that they match (i.e. there is a corresponding closing brace for an
opening brace). Proper indentation of the blocks should also be made.
In the above example, we see that there are two approaches for a multi way decision. In the first approach, we use
as many if statements as needed. This is an expensive approach. The second is the use of nested if statements. The
second is little more efficient than the first one. In the 'nested if statements' the nested else is not executed if the
first if condition is true and the control goes out of the if block.
The C language provides us a stand-alone construct to handle these instances. This construct is switch structure.
The switch structure is a multiple-selection construct that is used in such cases (multi way decisions) to make the code
more efficient and easy to read and understand.
The break statement interrupts the flow of control. We have seen in switch statement that when a true case is
found, the flow of control goes through every statement down ward. We want that only the statements of true case
should be executed and the remaining should be skipped. For this purpose, we use the break statement. We write the
break statement after the statements of a case. Thus, when a true case is found and its statements are executed then
the break statement interrupts the flow of control and the control jumps out of the switch statement. If we want to do
the same task for two cases, like in previous example for ‘A’ and ‘a’, then we don't put break statement after the first
case. We write both the cases (or the cases may be more than two) line by line then write the common statements to
be executed for these cases. We write the break statement after these common statements. We should use
the break statement necessarily after the statements of each case. The break statement is necessary
in switch structure, without it the switch structure becomes illogic. As without it all the statement will execute after first
match case is found.
The above code does nothing if the grade is other than these five categories (i.e. A, B, C, D and F). To handle all
the possibilities of grade input, we write a default statement after the last case. The statement in this default case is
executed if no case matches the grade. So in our program, we can write the default statement after the last case as
under.
{
cout << “Great, Your guess is correct” ;
break;
}
Up to now we have covered the basic programming constructs. These include sequences, decisions and repetition
structures (i.e. loops). In sequences, we use the simple statements in a sequence i.e. one after the other. In decisions
construct we use the if statement, if/else statement, the multi way decision construct (i.e. the switch statement). And in
repetition structures, we use the while, do-while and for loops.
Sometime ago, two computer scientists Gome and Jacopi proved that any program can be written with the help of
these three constructs (i.e. sequences, decisions and loops).
There is a statement in the computer languages COBOL, FORTRON and C. This statement is goto statement.
The goto is an unconditional branch of execution. The goto statement is used to jump the control anywhere (back and
forth) in a program. In legacy programming, the programs written in COBOL and FORTRAN languages have many
unconditional branches of execution. To understand and decode such programs that contain unconditional branches is
almost impossible. In such programs, it is very difficult, for a programmer, to keep the track of execution as the control
jumps from one place to the other and from there to anywhere else. We call this kind of traditional code
as spagatti code. It is very difficult to trace out the way of execution and figure out what the program is doing. And
debugging and modifying such programs is very difficult.
When structured programming was started, it was urged not to use the goto statement. Though goto is there in C
language but we will not use it in our programs. We will adopt the structured approach. All of our programs will consist
of sequences, decisions and loops.
GUIDE LINES
In general, we should minimize the use of break statement in loops. The switch statement is an exception in this
regard where it is necessary to use the break statement after every case. Otherwise, there may be a logical error.
While writing loops, we should try to execute the loops with the condition test and should try to avoid
the break statement. The same applies to the continue statement. The continue statement executes some statements
of the loop and then exits the loop without executing some statements after it. We can use the if statement for this
purpose instead of continue. So never use the goto statement and minimize the usage
of break and continue statements in loops. This will make the code easy to understand for you and for others.
Moreover the additions and modifications to such code will be easy, as the path of execution will be easy to trace.
Make a program modular. This means that divide a large program into small parts. It will be easy to manage these
small parts rather than a larger program. There should be single entry and single exit in every module or construct. The
use of break statement in a construct violates this rule as a loop having a break statement can exit
through break statement or can terminate when the loop condition violates. As there are two exit points, this should be
avoided. The single entry- single exit approach makes the execution flow simple.
Here is an example from daily life, which shows that single entry and single exit makes things easy. You would
have often seen at a bus stop, especially in rush hours, that when a bus reaches the stop, everyone tries to jump into
the bus without caring for others. The passengers inside the bus try to get down from the vehicle. So you see there a
wrestling like situation at the door of the bus. Separate doors for entering or exiting the bus can be the solution. In this
way, the passengers will easily enter or exit the bus.
We have applied this single entry and single exit rule in drawing our flow charts. In the flow charts, we draw a
vertical line from top to down. The point where the line starts is our entry point and downward at the same line at the
end is our exit point. Our all other processes and loops are along or within these two points. Thus our flow charts
resemble with the code.
RULES FOR STRUCTURED PROGRAMMING / FLOW CHARTING
There are few simple rules for drawing structured flow charts of programs. One should be familiar with these.
Rule No:1- Start with the simple flow chart. This means draw a start symbol, draw a rectangle and write in it
whatsoever you want to do and then draw a stop symbol. This is the simplest flow chart.
Rule No:2- Any rectangle ( a rectangle represents a process which could be input, output or any other process) can
be replaced by two rectangles.
This concept is the same as taking a complex problem and splitting it up into two simpler problems. So we have
‘split it up’ method to move towards a modular approach. So start with a block (rectangle) and then any rectangle can
be replaced by two rectangles (blocks).
Rule No:3- Any rectangle can be replaced with a structured flow charting construct. These construct include
decisions, loops or multi- way decision.
This means that we can put a structure of an if construct or switch construct in the place of a rectangle. Here we
come to know the advantage of single entry and single exit concept. This single entry and single exit block can be
replaced with a rectangle.
Rule No: 4- This rule states that rule number 2 and 3 can be repeated as many times as you want.
By using these rules we are splitting a problem into simpler units so that each part can be handled either by
sequences (one rectangle, second rectangle and so on) or by a decision (if, if/else, switch or by a loop). Through this
approach, a large problem can be solved easily.
The flow charts drawn with these rules and indented to the left side will have one to one correspondence with our code.
Thus it becomes very easy to identify the code that is written for a specific part of the flow chart. In this way the code
can easily be debugged.
Sample Program
Let’s consider a problem. In a company, there are deductions from the salary of the employees for a fund.
Take salary input from user and after appropriate deduction show the net payable amount.
Solution
As we see that there is multi way decision in this problem, so we use switch statement. The salary is the switch
variable upon which the different decisions depend. We can use only a single constant in case statement. So we
divide the salary by 10000 to convert it into a single case constant. As we know that in integer division we get the
whole number as the answer. Thus if answer is 0 the salary is less than 10000, if answer is 1 then it is in range
10000 to 19999 ( as any amount between 10000 – 19999 divided by 10000 will result 1). If the answer is greater
than 1, it means the salary is equal to or more than 20000.
Following is the complete code of our program.
// This program gets salary input from user and calculates and displays the net
payable
// amount after deduction according the conditions cout << salary << “ - ” << deduction << “ = “ << netPayable;
# include <iostream.h> break; //necessary to exit switch
main ( ) default : // this means the salary is 20,000 or more
{ deduction = salary * 7 /100 ;
int salary ; netPayable = salary – deduction ;
float deduction, netPayable ; cout << “Net Payable (salary – deduction) = “ ;
cout << “Please enter the salary : “ ; cout << salary << “ - ” << deduction << “ = “ << netPayable;
cin >> salary ; }
// here begins the switch statement }
switch ( salary / 10000 ) // this will produce a single value
{ Here is the out put of the program.
case 0 : // this means salary is less than 10,000
deduction = 0; // as deduction is zero in this case
netPayable = salary ;
cout << “Net Payable (salary – deduction) = “ ;
cout << salary << “ - ” << deduction << “ = “ << netPayable;
break; //necessary to exit switch
case 1 : // this means salary is in range 10,000 – 19,999
deduction = 1000 ;
netPayable = salary – deduction ;
cout << “Net Payable (salary – deduction) = “ ;
TIPS