Lab C++ 04 - Flow Control And Branching

  • Uploaded by: safuan_alcatra
  • 0
  • 0
  • May 2020
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Lab C++ 04 - Flow Control And Branching as PDF for free.

More details

  • Words: 2,367
  • Pages: 7
UNIVERSITI KUALA LUMPUR MALAYSIA FRANCE INSTITUTE

Lab 04 – Simple Flow of Control A. if Statement if ... else Statement In the programs you have seen so far, we have had a list of statements, which were executed in the order that they were written in your program (the .cpp file). In more complicated programs, you may need to change the order in which statements are executed. The order of execution for statements in your program is referred to as flow of control. Let's look at one example. Suppose you are organizing an event that costs $12 for everyone older than 8 and $6 for any one 8 years or younger. One way to do this is to say the ticket is $12, unless you are 8 or younger, then it is $6. In this case, you can write: Pseudo Code (English like statement) ticket = 12; if(age is 8 or younger) ticket = 6;

C++ equivalent double ticket = 12.00, age; if(age <= 8) ticket = 6;

There is another way to do this. Pseudo Code (English like statement) if(age is 8 or younger) ticket = 6; else ticket = 12;

C++ equivalent if(age <= 8) ticket = 6; else ticket = 12;

Both of these do the same thing. In both cases, you will change the flow of execution when you reach the statement; "age is 8 or younger". If that statement happens to be true, i.e., age is 8 or younger, then the value of ticket will change to $6, otherwise, you will go with its initialized value of $12. In general, the statement in the parentheses is either TRUE or FALSE. Depending on that being true or false, you will change the flow of execution of the statements in the program. In order for your program to decide about the flow of the execution, it uses a comparison operator. Examples of comparison operators are: 1. equal to , = , which will be written as == (2 ='s) in C++, with a general form of: statement1== statement2. Example: y == x + 1 2. not equal to , , which will be written as != in C++, with a general form of: statement1!= statement2. Example: y != x + 1 3. less than , <, which will be written as < in C++, with a general form of: statement1< statement2. Example: y < x + 1

UNIVERSITI KUALA LUMPUR MALAYSIA FRANCE INSTITUTE

4. less than or equal to , , which will be written as <= in C++, with a general form of: statement1<= statement2. Example: y <= x + 1 5. greater than , >, which will be written as > in C++, with a general form of: statement1> statement2. Example: y > x + 1 6. greater than or equal to , , which will be written as >= in C++, with a general form of: statement1>= statement2. Example: y >= x + 1 7. OR, which will be written as || (2 of the |'s) in C++, with a general form of: statement1|| statement2. Which may be True when either one of the two statements are TRUE. 8. AND, which will be written as && (2 of the &'s) in C++, with a general form of: statement1 &&statement2. Which may be True ONLY when both statements are TRUE. Now that you have learned about changing the flow of control, let's write a program called ticket.cpp that asks users to enter an age and displays the cost of the ticket based on the criteria that was given above. Use both methods to make sure // ticket.cpp - This program asks for an age and displays the cost of the ticket #include using namespace std; int main( ) { double age, ticket = 12; cout << "Please enter the age \n"; cin >> age; if(age <= 8) ticket = 6; cout << "Your ticket costs " << ticket << endl; return 0; }

Lab Exercise 1 Change the ticket.cpp program such that it displays $6 for people who are 8 years old or younger OR 65 years or older.

UNIVERSITI KUALA LUMPUR MALAYSIA FRANCE INSTITUTE

B. while ... loop Statement do ... while Statement The following C++ program computes the average of 6 numbers. // P23_1.cpp - Read and compute the average for 6 integers, display the result. #include using namespace std; int main(void) { int x,y,z, p, q, r; double average;

// (A)

// prompt the user: cout << "Enter six grades separated by spaces, then press Enter>:"; cout << endl; // read and store six integers: cin >> x >> y >> z >> p >> q >> r; // (B) average = (x + y + z + p + q + r)/6; // (C) cout << "The average is " << average << endl; return 0; }

If we wanted to compute the average of three numbers, we could make some changes in this program. The major changes will made in the lines that are in blue font, also, marked with (A), (B), and (C). Imagine, computing the average of 1000 numbers using the above program and method. That would make things more complicated and the code more tedious. We can simplify this computation using a loop. Following is a new version of the above program written using a while loop. An Example for while loop // P23_2.cpp - Read and average 6 integers, print the result. #include using namespace std; int main(void) { int x; int count = 0; // (1) initialize a counter to 0 to count number of grades double sum = 0; // initialize the sum to 0 to make sure the sum at the // beginning is 0 double average; // prompt the user: cout << "Enter six grades separated by a single space, then press”; cout << “ Enter>:”; while( count < 6) // (2) read six grades and compute their sum, count //ensures 6 entries { // read each number and compute the sum: cin >> x; sum = sum + x; count++; // (3) update the count } cout << endl; average = sum/6 6; // compute the average, total divided by the number // of grades cout << "The average is " << average << endl; return 0; }

UNIVERSITI KUALA LUMPUR MALAYSIA FRANCE INSTITUTE

What are the differences between this program and the one given in P23_1.cpp? Lab Exercise 2 Use a text editor to create a file called ex23_1.cpp. Copy and paste or carefully copy P23_2.cpp program in that file, and then change the program to compute the average of 100 numbers. Looping with Variable Number of Loops There are times that you do not know, up front, how many times a computation must be done. For example, you do not know how many numbers are going to be entered every time that you run the program. Thus, you want to make the loop flexible. Here is another version of the above program with variable number of loops. Suppose the user first provides number of values for which he/she wants to find the average, then he/she would enter those values. // P23_3.cpp - Read and average N integers, print the result. #include using namespace std; int main(void) { int x; int count = 0; // (1) initialize a counter to 0 to count number of values int N; // Number of values for which the average must be computed. double sum = 0; // initialize the sum to 0 to make sure the sum at the //beginning is 0 double average; // prompt the user: cout << "Enter number of values, N, to be read in <Enter>:" << endl; cin >> N; while( count < N) // (2) read N grades and compute their sum, count ensures // N entries { // read each number and compute the sum: cout << "\n Enter a grade <Enter>: "; cin >> x; sum = sum + x; count++; // (3) update the count } if(N N == 0) { cout << "You haven't enter 0 number, no average will be “; cout << “computed, bye \n"; } else{ average = average = sum/N N; out << "The average of these " << N << " grades is " << average << endl; } return 0; }

Remarks There are two types of loops. The first type are controlled by a counter and they are referred to as "count-controlled" loops. The second type are controlled by a particular event and they are referred to as "event-controlled" loops. In this lab, most of the examples are for count-controlled loops. In either case, there is always a boolean expression that leads the flow of the computation into the body of the loop or out of it.

UNIVERSITI KUALA LUMPUR MALAYSIA FRANCE INSTITUTE

To explain the difference between these two types of loops, let's look at the following two examples: A) Read 10 integers and compute their sum. A counter must keep the count until 10 numbers are read. B) Read integers and compute their sum for as long as the user keeps entering an integer value and stops once the user enters a letter. In this case, the event that stops the loop is the occurrence of a letter. In either case, if you wish to have a good working loop (any loop), there are three things that you have to always remember: 1) initialization, whatever controls the loop and is checked by the boolean expression, 2) valid condition, the boolean expression must correctly check the controlling variable, and 3) change, the controlling variable must be changed so that the boolean expression checks a new condition each time. If the condition does not change in the body of the loop, then the loop checks the same thing infinite number of times and you will have an infinite loop. Your program never stops and you have to terminate it using Ctrl-C or by killing the process. I am sure we will run into this problem in the lab, so you will learn how. These three things are marked with (1), (2) and (3), in the P23_2.cpp and P23_3.cpp programs. The syntax for a while loop is: while( Boolean_Expression) { Statement 1; Statement 2; ... Statement Last; }

The part between { and } is called the body of the loop. In a while loop, the body of the loop may be executed 0 times. That means, if the boolean expression evaluates to false right at the beginning, then the body of the loop will not get executed. Sometimes, you may want to execute the body of the loop at least once. In such a case you have to use a do while loop. The syntax for a do while is: do {

Statement 1; Statement 2; ... Statement Last; } while( Boolean_Expression);

UNIVERSITI KUALA LUMPUR MALAYSIA FRANCE INSTITUTE

Lab Exercise 3 Change program P23_3.cpp to work with a do while loop instead of while loop. Call your new program ex23_4.cpp, compile and run the program and make sure it produces the correct results. C. Simple Flow of Control Event-controlled while and do ... while loops In the previous parts, you learned to use a while loop with fix number of loops and then with variable number of loops. In both cases, you used a counting mechanism to stop the looping. There are times that you want to use a condition to stop the looping. For example, in the previous program, suppose you want to ask the user to see whether he/she wishes to enter a new grade. For now, we will use an integer to control the looping number. Here, the user will enter a 1 if he/she wishes to loop one more time and will enter a 0 or any other number to stop the looping. // P24_1.cpp - Read and average some integers, print the result. // This program continue asking for a new number until the user enters a 0 to terminate the program #include using namespace std; int main(void) { int x; int count = 0; // int choice = 1; // // double sum = 0; // // double average;

(1) initialize a counter to 0 to count number of values This is the choice that controls the looping continuation or termination initialize the sum to 0 to make sure the sum at the beginning is 0

while( choice == 1) // (2) read N grades and compute their sum, count //ensures N entries { // read each number and compute the sum: cout << "\n Enter a grade <Enter>: "; cin >> x; sum = sum + x; count++; // (3) update the count // prompt the user: cout << "Do you wish to enter another grade? “; cout << "(1 for yes and 0 or other key for no): " << endl; cin >> choice; } if(count == 0) cout << "You haven't entered any number, no average will be computed,” << “bye \n"; else{ average = sum/count; //Notice that we have divided by count this time cout << "The average of these " << count << " grades is " << average << endl; } return 0; }

Lab Exercise 3 In program 24_1.cpp, right at the beginning you have initialized the choice to 1. You did that to get the while loop to run at least once. If you use a do ... while instead, you wouldn't need to initialize the choice. Re-write the above program, call the new program

UNIVERSITI KUALA LUMPUR MALAYSIA FRANCE INSTITUTE

ex24_1.cpp, so that is uses do ... while. Do not initialize the choice to 1 this time and compile and run the program. Does the program work the same way? Lab Exercise 4 Write a complete C++ program that outputs the numbers 1 to 20, one per line. The program does nothing else. Lab Exercise 5 Write a complete C++ program that asks the user for a number of gallons and then outputs the equivalent number of liters. There are 3.78533 liters in a gallon. Use a declared constant. Since this is just an exercise, you need not have any comments in your program.

Related Documents