<Previous Lesson

Introduction to Programming

Next Lesson>

Lesson#8

Lesson 8

Summary


o Switch Statement
o Break Statement
o Continue Statement
o Guide Lines
o Rules for structured Programming/Flow Charting
o Sample Program
o Tips
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 underCS201
– Introduction to Programming

Page 68
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.
Page 69
The syntax of switch statement is as follows.
switch ( variable/expression )
{
case constant1 : statementLlist1 ;
case constant2 : statementLlist2 ;
:
:
case constantN : statementListN ;
default : statementList ;
}
In the switch statement, there should be an integer variable (also include char) or an
expression which must evaluate an integer type (whole numbers only, the decimal
numbers 2.5, 14.3 etc are not allowed). We can’t use compound conditions (i.e. the
conditions that use logical operators && or ||) in switch statement and in case statements.
The constants also must be integer constants (which include char). We can’t use a
variable name with the case key word. The default statement is optional. If there is no
case
which matches the value of the switch statement, then the statements of default are
executed.
The switch statement takes the value of the variable, if there is an expression then it
evaluates the expression and after that looks for its value among the case constants. If the
value is found among the constants listed in cases, the statements in that statementList
are executed. Otherwise, it does nothing. However if there is a default (which is
optional), the statements of default are executed.
Thus our previous grade example will be written in switch statement as below.
switch ( grade )
{
case ‘A’ : cout << “Excellent” ;
case ‘B’ : cout << “Very Good” ;
case ‘C’ : cout << “Good” ;
case ‘D’ : cout << “Poor” ;
case ‘F’ : cout << “Fail” ;
}
We know that C language is 'case sensitive'. In this language, ‘A’ is different from ‘a’.
Every character has a numeric value which is stored by the computer.. The numeric value
of a character is known as ASCII code of the character. The ASCII code of small letters
(a, b, c etc ) are different from ASCII code of capital letters (A, B, C etc). We can use
characters in switch statement as the characters are represented as whole numbers inside
the computers.
Now we will see how the use of ' the letter a' instead of 'A' can affect our program. We
want our program to be user- friendly. We don’t want to restrict the user to enter the
grade in capital letters only. So we have to handle both small and capital letters in our
Page 70
program. Here comes the limitations of switch statement. We can’t say in our statement
like
case ‘A’ or ‘a’ : statements ;
We have to make two separate cases so we write
case ‘A” :
case ‘a’ :
statements;
In the switch statement, the cases fall through the case which is true. All the statements
after that case will be executed right down to the end of the switch statement. This is very
important to understand it. Let's suppose that the user enters grade ‘B’. Now the case ‘A’
is skipped. Next case ‘B’ matches and statement cout << “Very Good” ; is executed.
After that, all the statements will be executed. So cout << “Good” ; cout << “Poor”
;and cout << “Fail” ; will be executed after one another. We don’t want this to happen.
We want that when a case matches, then after executing its statement, the control should
jump out of the switch statement leaving the other cases. For this purpose we use a key
word break.

Break Statement


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.
default : cout << “Please enter grade from A to D or F ” ;
The break statement is also used in decision structures other than switch structure. We
have seen that in while, do-while and for loops, we have to violate some condition
explicitly to terminate the loop before its complete repetitions. As in a program of
guessing a character, we make a variable tryNum greater than 5 to violate the while
Page 71
condition and exit the loop if the correct character is guessed before five tries. In these
loops, we can use the break statement to exit a loop. When a break statement is
encountered in a loop, the loop terminates immediately. The control exits the inner most
loop if there are nested loops. The control passes to the statement after the loop. In the
guessing character example, we want that if the character is guessed in first or second
attempt,. then we print the message ‘Congratulations, You guess is correct’ and exit the
loop. We can do this by using a break statement with an if statement. If the character is
guessed, we print the message. Afterwards, the break statement is executed and the loop
terminates. So we can write this as follows.
if ( c == ‘z’ ) // c is input from user
{
cout << “Great, Your guess is correct” ;
break;
}
Thus, break statement can be used to jump out of a loop very quickly.
The flow chart of the switch statement is similar to if statement and is given below.
switch
(variable )
Process
Process
case
const 1
case
const2
break
break

The flow chart of switch statement


The number of case statement can vary from
1 to any number. Thus there are same
number of process blocks as cases.

Now we can write the complete code for the program that prints the description of the
grade entered by the user.
The flow chart of the program is given below.
Page 72
Start
switch (grade)
Stop
Display "Excellent"
case 'A'
break
Display
"Very Good"
case 'B'
break
Display "Good"
case 'C'
break
Display "Poor"
case 'D'
break
Display "Fail"
case 'F'
break
Display " Please
enter grade A-D or
F"
default
break

The flow chart of a program that displays the description of a grade
using switch statement


Page 73
The code of the program is given below.
//This program gets a grade from user and displays a description accordingly
# include <iostream.h>
main ( )
{
char grade ;
cout << “Please enter the student’s grade : ” ;
cin >> grade ;
switch ( grade )
{
case ‘A’ : // grade was upper case A
case ‘a’ : // grade was lower case a
cout << “Excellent” ;
break : // necessary to exit switch
case ‘B’ : // grade was upper case B
case ‘b’ : // grade was lower case b
cout << “Very Good” ;
break : // necessary to exit switch
case ‘C’ : // grade was upper case C
case ‘c’ : // grade was lower case c
cout << “Good” ;
break : // necessary to exit switch
case ‘D’ : // grade was upper case D
case ‘d’ : // grade was lower case d
cout << “Poor” ;
break : // necessary to exit switch
case ‘F’ : // grade was upper case F
case ‘f’ : // grade was lower case f
cout << “Fail” ;
break : // necessary to exit switch
default :
cout << “Please enter grade from A to D or F ” ;
}
}
A sample out put of the program is shown here.
Please enter the student’s grade : b
Very Good
continue Statement

There is another statement relating to loops. This is the continue statement. Sometimes
we have a lot of code in the body of a loop. The early part of this code is common that is
Page 74
to be executed every time (i.e. in every iteration of loop) and the remaining portion is to
be executed in certain cases and may not be executed in other cases. But the loop should
be continuous. For this purpose, we use the continue statement. Like the break statement,
the continue statement is written in a single line. We write it as
continue ;
The continue forces the immediate next iteration of the loop. So the statements of the
loop body after continue are not executed. The loop starts from the next iteration when a
continue
statement is encountered in the body of a loop. One can witness very subtle
things while using continue.
Consider the while loop. In while loop, we change the value of the variable of while
condition so that it could make the condition false to exit the loop. Otherwise, the loop
will become an infinite one. We should be very careful about the logic of the program
while using continue in a loop. Before the continue statement, it is necessary to change
(increment/decrement) the value of the variable on which the while condition depends.
Similarly it is same with the do-while loop. Be careful to increment or decrement the
conditional variable before the continue statement.
In for loop, there is a difference. In a while loop when continue is encountered, the
control goes to the while statement and the condition is checked. If condition is true the
loop is executed again else the loop exits. In a for loop, the three things i.e. initialization,
condition and increment/decrement are enclosed together as we write for ( counter = 0 ;
counter <= 5 ; counter ++)
. In the for loop when a continue is encountered, the counter
(i.e. loop variable) is incremented at first before the execution of the loop condition.
Thus, in 'for loop' the increment to the loop variable is built in and after continue the next
iteration of the loop is executed by incrementing the loop variable. The condition is
checked with the incremented value of the loop variable. In while and do-while loop, it is
our responsibility to increment the value of the loop variable to test the condition. In a for
loop, the continue automatically forces this increment of value before going to check the
condition.

goto Statement


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
Page 75
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.
Page 76

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 that 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. The deductions rules are as follows:
i) If salary is less than 10,000 then no deduction
ii) If salary is more than 10,000 and less than 20,000 then deduct Rs. 1,000 as
fund
iii) If salary is equal to or more than 20,000 then deduct 7 % of the salary for 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
Page 77
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
# include <iostream.h>
main ( )
{
int salary ;
float deduction, netPayable ;
cout << “Please enter the salary : “ ;
cin >> salary ;
// here begins the switch statement
switch ( salary / 10000 ) // this will produce a single value
{
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) = “ ;
cout << salary << “ - ” << deduction << “ = “ << netPayable;
break; //necessary to exit switch
default : // this means the salary is 20,000 or more
deduction = salary * 7 /100 ;
netPayable = salary – deduction ;
cout << “Net Payable (salary – deduction) = “ ;
cout << salary << “ - ” << deduction << “ = “ << netPayable;
}
}
Here is the out put of the program.
Please enter the salary : 15000
Net Payable (salary – deduction) = 15000 – 1000 = 14000
Page 78

Tips


Try to use the switch statement instead of multiple if statements
Missing a break statement in a switch statement may cause a logical error
Always provide a default case in switch statements
Never use goto statement in your programs
Minimize the use of break and continue statements

<Previous Lesson

Introduction to Programming

Next Lesson>

Home

Lesson Plan

Topics

Go to Top

Copyright © 2008-2013 zainbooks All Rights Reserved
Next Lesson
Previous Lesson
Lesson Plan
Topics
Home
Go to Top