UNIVERSITI KUALA LUMPUR MALAYSIA FRANCE INSTITUTE
Lab 07 – More Flow of Control PRE LAB Answer the following questions in writing: 1) Write a C++ program segment that displays the amount of tax, based on the following tax table. Assume that the income has already been entered from the keyboard.
More than
Less than or Equal to %Tax
$0
$ 18,000
0
$ 18,000
$ 30,000
10
$ 30,000
$ 45,000
12.5
$ 45,000
$ 60, 000
15
$ 60,000
$ 80,000
17.5
$ 80,000
20
2) In C++ you can declare a variable at any point of the program. Do you think the following code segment will result in a syntax error? If not, what would be the output of the program? int x = 12; { int x = 3; cout << "1st " << x << endl; } cout << "2nd " << x << endl;
3) Suppose you have a while loop that executes many times, but you want to exit the loop if a certain condition occurs. How do you get out of a loop before the maximum number of loops is reached.
UNIVERSITI KUALA LUMPUR MALAYSIA FRANCE INSTITUTE
A. Using Boolean Expressions The order in which the statements in a program are performed is called flow of control. In the previous labs, you saw programs in which if, if...else, while, and do ... while statements were used. These statements were used to specify flow of control in your programs. The concept behind all these methods is the same, your program comes to a statement that is either true or false. Such a statement is called a Boolean expression. The program then will perform a different task depending on the statement being true or false. For example: Suppose somewhere in your program you have: if( x < 10 && y > 12 12).
In this statement, the Boolean expression is x < 10 && y > 12. This expression is true or false. Of course, there are several possibilities here: Possibility 1: x >= 10 and y <= 12 Possibility 2: x >= 10 and y > 12 Possibility 3: x < 10 and y <= 12 Possibility 4: x < 10 and y > 12
the expression will be: false the expression will be: false the expression will be: false the expression will be: true
So your program will go one way when the expression evaluates to false and another way when the expression evaluates to true. So its flow is controlled by this Boolean expression. Note that the expression inside ( ) in the if statement can be very simple or very complicated. But, in either case that statement will evaluate to true or false, regardless of its complexity. When an expression is complex, your compiler uses the precedence rules to decide the order in which each different part of the expression should be executed. In the following expression, for example, the order of execution is decided by these rules: if ( (x + 2) > 3 || (x + 1) < -3 ) will be executed in this order: if ( ((x + 2) > 3) || ((x + 1) < -3) ) The rules are listed in Display 7.2 of the textbook. Here, first the expression ((x + 2) > 3) will be evaluated and then the expression ((x + 1) < -3). Because there is an OR, "| |", between the two expressions, if the first one evaluates to true, the second one never gets evaluated. This is because, in an OR expression, once either one of the two expressions is true, the entire expression evaluates to true. Exercise 1 Following is a list of some Boolean expressions. Carefully go through each one of them and determine whether they evaluate to true or false. A: B: C: D:
Expression ( (count == 0) && (limit < 20)) ( count == 0 && limit < 20 ) ( (limit > 12) || (count < 5) ) ( !(count == 5) )
Answer
UNIVERSITI KUALA LUMPUR MALAYSIA FRANCE INSTITUTE
E: ( (count == 1) && (x < y) ) F: ( (count < 10) || (x < y) ) G: ( !( ((count < 10) || (x < y)) && (count >= 0)) ) H: ( ((limit/count) > 7) || (limit < 20) ) I: ( (limit < 20) || ((limit/count) > 7) ) J: ( ((limit/count) > 7) && (limit < 0) ) K: ( (limit < 0) && (( limit/count) > 7) ) L: ( (5 && 7) + (!6) ) Now, create a file ex71.cpp and cut and paste the following program in it. Compile and run the program and see how well your answers to the above expressions match the program's output. // ex71.cpp - This program illustrates the Boolean expressions and the // order of precedence #include
using namespace std; int main() {
int count = 0, limit = 10; int x,y; cout cout cout cout cout cout cout cout cout cout cout cout
<< << << << << << << << << << << <<
"a "b "c "d "e "f "g "h "i "j "k "l
" " " " " " " " " " " "
<< << << << << << << << << << << <<
( ( ( ( ( ( ( ( ( ( ( (
(count == 0) && (limit < 20)) << "\n"; count == 0 && limit < 20 ) << "\n"; (limit > 12) || (count < 5) ) << "\n"; !(count == 5) ) << "\n"; (count == 1) && (x < y) ) << "\n"; (count < 10) || (x < y) ) << "\n"; !( ((count < 10) || (x < y)) && (count >= 0)) ) << "\n"; ((limit/count) > 7) || (limit < 20) ) << "\n"; (limit < 20) || ((limit/count) > 7) ) << "\n"; ((limit/count) > 7) && (limit < 0) ) << "\n"; (limit < 0) && (( limit/count) > 7) ) << "\n"; (5 && 7) + (!6) ) << "\n";
return 0; }
Note that some of the statements may cause run-time errors. Find those statements and explain why the errors have happened. To make the program go to the next statement, simply comment (//) the line that causes the run-time error. Recompile and run the program again until all lines that cause a run-time error are commented. What is the difference between h and i?
Would it make any difference if in "j" we switch the first and the second statements, i.e., we use: cout << "j
" << ( (limit < 0) && ((limit/count) > 7)
) << "\n";
UNIVERSITI KUALA LUMPUR MALAYSIA FRANCE INSTITUTE
B. if ... else if ... else Statement switch Statement You learned to change the flow of your program using if ... else statements. The if ... else statement deals with situations where there are two options and you take one or the other depending on the outcome of the Boolean expression. However, sometimes you may run into a situation where you have more than two choices. Think about an elevator. You enter an elevator and, if the building has 4 floors and a basement, like mine does, you have 5 choices. For now we think of a simple elevator, but more sophisticated ones may also have a button to close or to open the door. As you can imagine, if you enter an elevator and do not press a key, the door will close but you will not move anywhere. So the default action is actually the close door action. Of course, sometimes you may enter an elevator and do not push a button, then someone from another floor may press the button outside and lead the elevator to where he/she stands. As you can see, the button outside an elevator is up or down and that is a good example of if ... else, but inside the elevator, you need a more sophisticated statement to control the flow. We will use if ... else if ... else statement for inside. Following is a program that simulates a simple elevator. // P71.cpp - A simple elevator for 4 floors and a basement with a // close door button and 5 keys for floors #include #include using namespace std; void close_door(); int change_floor(int choice, int floor); int main( ) { int key; int floor = 0; cout << "Press a Key \n"; cin >> key; if(key == 0) { close_door(); if( floor != 0){ // otherwise nothing happens cout << "I am moving to the Basement \n"; floor = change_floor(0, floor); } } else if(key == 1) { close_door(); if( floor != 1){ // otherwise nothing happens cout << "I am moving to the the First Floor \n"; floor = change_floor(1, floor); } } else if(key == 2) { close_door(); if( floor != 2){ // otherwise nothing happens cout << "I am moving to the the Second Floor \n"; floor = change_floor(2, floor); } } else if(key == 3) { close_door(); if( floor != 3){ // otherwise nothing happens
UNIVERSITI KUALA LUMPUR MALAYSIA FRANCE INSTITUTE
cout << "I am moving to the the Third Floor \n"; floor = change_floor(3, floor); } } else if(key == 4) { close_door(); if( floor != 4){ // otherwise nothing happens cout << "I am moving to the the Fourth Floor \n"; floor = change_floor(4, floor); } } else { close_door(); } return 0; } void close_door() { cout << "I am closing the door \n"; } int change_floor(int choice, int floor) { int move; move = floor - choice; // Note floor = choice is already considered in main if(move < 0) { cout << "Move up by " << abs(move) << endl; } else { cout << "Mode down by " << abs(move) << endl; } floor = choice; cout << "You are at floor " << floor << endl; return floor; }
Exercise 2 Write the above program using if and if ... else statements and call your new program ex71.cpp. In other words, replace the if ... else if ... ... else statements with if or else statements. Can you explain the advantage of using if ... else if ... else instead of if statements?
switch Statement Switch statements can be used for multiway branches similar to the if ... else if ... else statement used in the previous example. The syntax for a switch statement is given below: switch (controlling_Expression) { case constant_1: statement sequence for case 1 break; case constant_2: statement sequence for case 2
UNIVERSITI KUALA LUMPUR MALAYSIA FRANCE INSTITUTE
break; .... .... .... default: statement sequence for the default case } In program P71.cpp, the controlling_Expression is variable key, because its value will control which branch to execute. In that program each if or else if statement is a separate case, and the else is the default case. Note that if you use the switch statement, you need to end each case with a break statement. If you leave a break out, then the next case will also be executed. This is a way to write the statements with AND. For example: The following segment: if( key == 1 && key == 2) { .... }
will be represented as: case 1: case 2: ..... break;
in a switch statement. Exercise 3 Modify the P71.cpp program and use a switch statement instead of the if ... else if ... else statement in the main. Call your new program ex73.cpp.
UNIVERSITI KUALA LUMPUR MALAYSIA FRANCE INSTITUTE
C. for statement You may remember when we introduced while loops, we mentioned that a good loop must have at least three things to work correctly: 1) the controlling variable must be initialized, 2) the Boolean expression must be valid and include the controlling variable, and 3) the controlling variable must be updated in the body of the loop. A for loop has all three of these between ( and ), here is how: for(initilization_Action; Boolean_Expression; Update_Action) { Statement_1 Statement_2 ... ... Statement_last }
The following program uses for loops to draw a rectangle of desired size. // P73.cpp - This program draws a rectangle n rows and m columns. // The program asks the user to input a character for drawing the rectangle #include using namespace std;
int main( ) { int rows, columns; char draw_char; cout << "Enter number of rows and columns \n"; cin >> rows >> columns; cout << "Enter the character to draw with \n"; cin >> draw_char; for(int i = 0; i < rows; i++) { for(int j = columns; j > 0; j--) { cout << draw_char; } cout << endl; } }
return 0;
As you can see in the above example, we have used two for loops one within the other. Such use of loops is known as nested loops. The loop inside is said to be faster because for every row, i, j will change columns times. The following program will display the days for a month of the year. The input to the program is the number of days and the day of the week on which the first day of the month falls.
UNIVERSITI KUALA LUMPUR MALAYSIA FRANCE INSTITUTE
The following program uses for loops to draw a rectangle of desired size. // // // //
P73a.cpp - This program displays the days of a month Day 0 : Sunday, Day 1: Monday, Day 2: Tuesday Day 3: Wednesday, Day 4: Thursday, Day 5: Friday Day 6: Saturday
#include #include using namespace std;
int main( ) { int n_days, start_day; cout << "Enter the number of days, 28, 29, 30 or 31 \n"; cin >> n_days; cout << "Enter the first day of the month \n"; cin >> start_day; cout << "Sun\tMon\tTue\tWed\tThr\tFri\tSat\n"; for(int i = 0; i < start_day; i++) { cout << " \t"; } for(int j = 1; j <= n_days; j++) { if( j%7 == 0) cout << endl;
}
cout << j } cout << endl; return 0;
<< "\t";
Exercise 4 Modify the above program such that it uses a function called display_month(int n_days, int start_day) to display the days of a month. Call your new program ex74.cpp. In the new program, replace the following segment: for(int i = 0; i < start_day; i++) { cout << " \t"; }
with a function, get_tabs(int start_day), that uses a switch statement with start_day as its Controlling_Expression to display the correct number of tabs.
UNIVERSITI KUALA LUMPUR MALAYSIA FRANCE INSTITUTE
D. Blocks and The Scope of a Variable in a Block Each branch of a switch statement or of an if statement does a separate task and is considered a block. Sometimes in a program you have a compound statement with multiple declarations of variables throughout the program. All variables declared inside a block are local to that block. Here is an example: // P74.cpp - This program illustrates the scope of variables in a block #include using namespace std; int main( ) { int x = 10; for(int i = 0; i < x; i++) { int x = 5; cout << "i = " << i << endl; } cout << "x = " << x << endl; }
return 0;
Exercise 5 Without compiling the above program, determine its output. Copy and paste or carefully copy the program in a file called P74.cpp. Compile and run the program and see if you have gotten the correct answer. Now, suppose in the program we replace the for loop with the following segment: for(int i = 0; i < x; i++) { x = 5; cout << "i = " << i << endl; }
What is the output of the program with this segment? Modify the program and see if you have gotten the correct answer.