






Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!







Deitel & Deitel – C++ How to Program Chapter 2
2.16, 2.
o Switch Statement o Break Statement o Continue Statem uide Lines
ent
Charting
witch Statement
metimes, we have multiple conditions and take some action according to each
is
as
t and display the appropriate description. We have five write five if statements to check we write this in our program as
o G o Rules for structured Programming/Flow o Sample Program o T ips
S
S o 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 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 h 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 statemen categories of grades-- A, B, C, D, and F. We have to all the five possibilities (probabilities) ofgrade. So under- if ( grade == ‘A’ ) cout << “Excellent” ; if ( grade == ‘B’ ) cout << “Very Good” ; if ( grade == ‘C’ ) cout << “Good” ; if ( grade == ‘D’ ) cout << “Poor” ;
hese statements are correct and perform the required task. But the ' if statement' is ne of the most expensive statements in a program. We call it xpensive due to the fact that the processor has to go through many cycles to execute
g
else if ( grade == ‘C’ )
out << “Fail” ;
n the code, there is single statement with each if statement. If there are more
r
switch ( variable/expression )
case constant1 : statementLlist1 ; case constant2 : statementLlist2 ;
case constantN : statementListN ; default : statementList ;
if ( grade == ‘F’ ) cout << “Fail” ;
T computationally o e 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 followin nested if/else form.
If ( grade == ‘A’ ) cout << “Excellent” ; else if ( grade == ‘B’ ) cout << “Very Good” ;
cout << “Good” ; else if ( grade == ‘D’ ) cout << “Poor” ; else if ( grade == ‘F’ ) c
I 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). Prope 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 syntax of switch statement is as follows.
docsity.com
at when a case matches, then after aving e other cases. For this purpose we use a key word break.
tement
he br interrupts the flow of control. We have seen in switch statement hrough every statement down ly the statements of true case should be executed and the emaining should be skipped. For this purpose, we use the break statement. We write ak statement after the statements of a case. Thus, when a true case is found and s statements a rupts the flow of control and s t to do the same task for two e for ‘A’ and ‘a’, then we don't put break statement
. We cases may be more than two) line for these cases. We write the reak statemen e co uld use the break statement of each case. The break statement is necessary in witch cture becomes illogic. As without it all the tateme t will er fi
e abo ing if the grade is other than these five categories (i.e. A, B, of grade input, we write a default tateme t after e. T case is executed if no case he g e can write the default statement after the
lease enter grade from A to D or F ” ;
statement is ctures other than switch structure. We while, do-while and for loops, we have to violate some condition ore its complete repetitions. As in a program of a character, we make a variable tryNum greater than 5 to violate the while is guessed before five tries. In these ps, we can use the break statement to exit a loop. When a break statement is ountered in a loop, the loop terminates immediately. The control exits the inner ost loop if there are nested loops. The control passes to the statement after the loop. the guessing character example, we want that if the character is guessed in first or ratulations, You guess is correct’ sing a break statement with an if statement. If is guessed, we print the message. Afterwards, the break statement is ecuted and the loop terminates. So we can write this as follows. m user
We don’t want this to happen. We want th executing its statement, the control should jump out of the switch statement le th
Break Sta
T eak statement that when a true case is found, the flow of control goes t ward. We want that on r the bre it re executed then the break statement inter the control jumps out of the witch statement. If we wan cases, like in previous exampl after the first case write both the cases (or the by line then write the common statements to be executed b t after thes mmon statements. We sho necessarily after the statements s structure, without it the switch stru s n execute aft rst match case is found.
Th ve code does noth C, D and F). To handle all the possibilities s n the last cas he statement in this default matches t rade. So in our program, w last case as under. default : cout << “P
The break also used in decision stru have seen that in explicitly to terminate the loop bef guessing condition and exit the loop if the correct character loo enc m In second attempt,. then we print the message ‘Cong and exit the loop. We can do this by u the character ex if ( c == ‘z’ ) // c is input fro { 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.
docsity.com
The flow chart of switch statement
The number of case statement can vary from 1 to any number. Thus there are same switch number of process blocks as cases. (variable )
case const 1
Process
case const
break
Process
break
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.
docsity.com
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” ;
case ‘B’ : // grade was upper case B
e ‘C’ : // grade was upper case C
case ‘D’ : // grade was upper case D ase ‘d’ : // grade was lower case d oor” ; break : // necessary to exit switch
break : // necessary to exit switch
case ‘b’ : // grade was lower case b cout << “Very Good” ; break : // necessary to exit switch cas case ‘c’ : // grade was lower case c cout << “Good” ; break : // necessary to exit switch
c cout << “P
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
There is another statement relating to loops. This is the continue statement.
and may not be executed in other ld be continuous. For this purpose, we use the continue k statement, the continue statement is written in a single line. it as continue ;
Sometimes we have a lot of code in the body of a loop. The early part of this code is common that is to be executed every time (i.e. in every iteration of loop) and the remaining portion is to be executed in certain cases cases. But the loop shou statement. Like the brea We write
he co n of the loop. So the statements of the e are not executed. The loop starts from the next iteration n the body of a loop. One can witness very ubtle things while using continue. ariable of while it could make the condition false to exit the loop. Otherwise, the e an in bout the logic of the ement, it is necessary crement) the value of the variable on which the while e careful to inue statement.
is encountered, the condition is checked. If condition is true for loop, the three things i.e. gether as we write when a continue is rst before the xecuti loop c nditio op variable of the loop is executed by incrementing he incremented value of the loop ariabl In wh rement the value of e automatically forces s increment of value before going to check the condition.
ic programming constructs. These include n structures (i.e. loops). In sequences, we use the ecisions construct we use e if statement, if/else statement , the multi way decision construct (i.e. the switch atement). And in repetition structures, we use the while, do-while and for loops. ometime ago, two computer scientists Gome and Jacopi proved that any program written with the help of these three constructs (i.e. sequences, decisions and ops). ON and C. This on. The (back and forth) in a program. In COBOL and FORTRAN languages 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
T ntinue forces the immediate next iteratio loop body after continu when a continue statement is encountered i s Consider the while loop. In while loop, we change the value of the v condition so that loop will becom finite one. We should be very careful a program while using continue in a loop. Before the continue stat to change (increment/de condition depends. Similarly it is same with the do-while loop. B increment or decrement the conditional variable before the cont
In for loop, there is a difference. In a while loop when continue control goes to the while statement and the the loop is executed again else the loop exits. In a initialization, condition and increment/decrement are enclosed to for ( counter = 0 ; counter <= 5 ; counter ++). In the for loop encountered, the counter (i.e. loop variable) is incremented at fi e on of the o n. Thus, in ' for loop' the increment to the lo is built in and after continue the next iteration the loop variable. The condition is checked with t v e. ile and do-while loop, it is our responsibility to inc the loop variable to test the condition. In a for loop, the continu thi
Up to now we have covered the bas sequences, decisions and repetitio simple statements in a sequence i.e. one after the other. In d th st S can be lo There is a statement in the computer languages COBOL, FORTR statement is goto statement. The goto is an unconditional branch of executi goto statement is used to jump the control anywhere legacy programming, the programs written in have many unconditional branches of execution. To
y
if construct or switch construct in the place of a rectangle. ere we come to know the advantage of single entry and single exit concept. This
n
code that
salary is equal to or more than 20,000 then deduct 7 % of the salary for fund input from user and after appropriate deduction show the net payable mount.
ment. So we divide the salary y 10000 to convert it into a single case constant. As we know that in integer division
swer is greater than 1, it eans the salary is equal to or more than 20000. rogram. This program gets salary input from user and calculates and displays the net payable mou e conditions
include
yable ; cout << “Please enter the salary : “ ;
// here begins the switch statement
approach. So start with a block (rectangle) and then any rectangle can be replaced b 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 H 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 ca 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 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: If salary is less than 10,000 then no deduction If salary is more than 10,000 and less than 20,000 then deduct Rs. 1,000 as fund If Take salary a
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 state b 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 an m Following is the complete code of our p // // a nt after deduction according th
main ( ) { int salary ; float deduction, netPa
cin >> salary ;
docsity.com
a single value { n 10, deduction = 0; // as deduction is zero in this case
cout << “Net Payable (salary – deduction) = “ ; out << salary << “ - ” << deduction << “ = “ << netPayable;
eduction = 1000 ; able = salary – deduction ;
switch ( salary / 10000 ) // this will produce
case 0 : // this means salary is less tha
netPayable = salary ;
c break; //necessary to exit switch case 1 : // this means salary is in range 10,000 – 19, d netPay 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
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
docsity.com