1 / 44

Chapter 5 – Repetition and Loop Statements

Chapter 5 – Repetition and Loop Statements. Jason C. H. Chen, Ph.D. Professor of MIS School of Business Administration Gonzaga University Spokane, WA 99258 chen@gonzaga.edu. Sum 100 values the hard/right way?. int sum = 0; cout << "Enter number: "; // <-Repeat these three

bambi
Download Presentation

Chapter 5 – Repetition and Loop Statements

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 5 – Repetition and Loop Statements Jason C. H. Chen, Ph.D. Professor of MIS School of Business Administration Gonzaga University Spokane, WA 99258 chen@gonzaga.edu

  2. Sum 100 values the hard/right way? int sum = 0; cout << "Enter number: "; // <-Repeat these three cin >> number; // <- statements for each sum = sum + number; // <- number in the set cout << "Enter number: "; cin >> number; sum = sum + number; /* ...297 statements omitted ... */ cout << "Enter number: "; cin >> number; sum = sum + number; average = sum / 100;

  3. Why iterate? • Use the computer's speed to do the same task faster than if done by hand. • Avoid writing the same statements over and over again. • Programs can be made general enough to handle other types of data.

  4. Repetitive control structures • Because many algorithms require many iterations over the same statements. • To average 100 numbers, we would need 300 plus statements. • Or we could use a statement that has the ability to repeat a collection of statements: • Pre test / Post test loops.

  5. Repetition and Loop Controls • while • for • do … while

  6. 5.1 Counting Loops and the while Statement • General form of the while statement: while (loop-test/logical expression) { iterative-part termination criteria } • When a while loop executes, the loop-test is evaluated. If true (non-zero), the iterative part is executed and the loop-test is reevaluated. This process continues until the loop test is false. • Pre test loop

  7. Collections of statements are delimited with { and } • while there is another number, do the following { cout << "Enter number: "; cin >> number; sum = sum + number; } average = sum / 100;

  8. Flowchart view of while loop initialization False True countEmp < 3 Get data Iterative Part Compute pay Display pay Inc countEmp by 1

  9. Figure 5.1: Program fragment with a loop (p. 227) numberEmp = 3; countEmp = 0; while (countEmp < numberEmp) { cout << "Hours: "; cin >> hours; cout << "Rate : $"; cin >> rate; pay = hours * rate; cout << "Pay is " << pay << endl << endl; totalPay += pay; // accumulate total pay countEmp++; } // end while cout << "All employees processed." << endl; cout << "Total payroll is " << totalPay << endl; Questions: (p. 229) What will happen if: a. If the update statement countEmp++; is omitted? b. if the initialization statement countEmp = 0; is omitted?

  10. Infinite loops • Infinite loop:a loop that never terminates. • Infinite loops are usually not desirable. • Here is an example of an infinite loop:

  11. Infinite loops (cont.) int counter = 1; int j = 0; int n = 3; while(counter <= n) { j = j + 1; cout << counter << endl; } cout << "Do we ever get here?" << endl; There is no step that brings us to termination.

  12. 5.2 Accumulating a Sum or Product in a Loop • Lets look at the idea of adding together a group of numbers • Many lines of the same statements • Sample code using loop

  13. while (countEmp < numberEmp) { cout << "Hours: "; cin >> hours; cout << "Rate : $"; cin >> rate; pay = hours * rate; cout << "Pay is " << pay << endl << endl; totalPay += pay; // accumulate total pay countEmp++; } // end while cout << "All employees processed." << endl; cout << "Total payroll is " << totalPay << endl; getch(); return 0; } // FILE NAME: computePay.cpp (p.231) // COMPUTES THE PAYROLL FOR A COMPANY #include <iostream> #include <iomanip> #include <conio.h> #include "money.cpp" int main () { // Local data ... int numberEmp; // input - number of employees int countEmp; // counter - current employee number float hours; // input - hours worked money rate; // input - hourly rate money pay; // output - weekly pay money totalPay; // output - company payroll // Get number of employees from user. cout << "Enter number of employees: "; cin >> numberEmp; cout << setiosflags (ios::fixed | ios::showpoint) << setprecision (2); // Compute each employee's pay and add it to the payroll. totalPay = 0.0; countEmp = 0;

  14. ComputePay.cpp Program Output Enter number of Employees: 3 Hours: 50 Rate: $5.25 Pay is: $262.5 Hours: 6 Rate: $5 Pay is: $30 Hours: 1.5 Rate: $7 Pay is: $105 Total payroll is $397.5 There are 3 employees processed. The average pay is: $132.5 Your turn: modify the program (computePayAve.cpp) to compute the average pay.

  15. What are they? Type casting • 1. C++ Syntax: while statement • General Form: • initialization; • while (logical expression) • { • statement_1; • termination criteria; • ... • } • int counter = 0, total_number = 0, score, sum =0; • float average; • cout << "Enter total number of scores will be processed: "; • cin >> total_number; • while (counter < total_number) • { • cout << "Enter the " << (counter+1) << " score: " ; • cin >> score; • sum += score; • cout << "Score " << (counter+1) <<":" << score << " current sum is: ” << sum << endl; • counter ++; • }// end while • average = float(sum) / float(total_number); • cout << "The sum is: " << sum << "the average is: " << average; • }//end main

  16. 5.3 The for Statement • The for loop is similar to the other C++ looping construct the while loop. • The for loop forces us to write, as part of the for loop, an initializing statement, the loop-test, and a statement that is automatically repeated for each iteration. • Pre test loop.

  17. General form of a for loop for(initial statement; loop-test ;repeated statement) { iterative-part } • When a for loop is encountered, the initial-statement is executed. The loop-test is executed. If the loop-test is false, the for loop is terminated. If loop-test is true, the iterative-part is executed and the repeated-statement is executed.

  18. Flowchart for a for loop Initial statement True False countEmp < 7 Get Data Compute Pay Display Pay Increase countEmp by 1

  19. Example for loop • This is a for-loop version of a counter-controlled loop : • Scope of the loop control variable: for (int counter = 1; counter<=5;counter = counter+1) { cout << counter << " "; } • Output: ________________________________? Exercise 5.3 (p.243) #1

  20. 2. C++ Syntax:forstatement • General Form: • for(initialization; test expression; update) • { • statement_1; • statement_2; • ... • } • int counter = 0, total_number = 0, score, sum =0; • float average; • cout << "Enter total number of scores will be processed: "; • cin >> total_number; • while (counter < total_number) • { • cout << "Enter the " << (counter+1) << " score: " ; • cin >> score; • sum += score; • cout << "Score " << (counter+1) <<":" << score << " current sum is: ” << sum << endl; • counter ++; • }// end while • average = float(sum) / float(total_number); • cout << "The sum is: " << sum << "the average is: " << average; • }//end main • Example ”for” loop: • for(int counter=0; counter < total_number; counter++) • { • cout << "Enter the " << (counter+1) << " score: " ; • cin >> score; • sum += score; • cout << "Score " << (counter+1) <<":" << score << " current sum is: " • << sum << endl; • } // endfor loop Re-write with for

  21. Other Incrementing Operators • The unary ++ and -- operators add 1 and subtract 1 from the operand, respectively. • int n = 0; • n++; // n is now 1 Equivalent to n=n+1; • n++; // n is now 2 • n--; // n is now 1 again • The expression n++; is equivalent to the longer n = n + 1; • It is common to see counter-controlled loops of this form where n is the number of reps

  22. 5.4 Conditional Loops • In many programming situations, you will not be able to determine the exact number of loop repetitions • Conditional Loop • Initialize the loop control variable • While a condition involving the loop control variable is true • Continue processing • Update the loop control variable

  23. Conditional Loops • Case Study: Monitoring Oil Supply • ProblemWe want to monitor the amount of oil remaining in a storage tank at the end of each day. The initial supply of oil in the tank and the amount taken out each day are data items. Our program should: 1) display the amount left in the tank at the end of each day and 2) it should also display a warning when the amount left is less than or equal to 10 percent of the tank’s capacity. At this point, no more oil can be removed until the tank is refilled.

  24. Conditional Loops • Analysis  Clearly, the problem inputs are the initial oil supply and the amount taken out each day. The outputs are the oil remaining at the end of each day and a warning message when the oil left in the tank is less than or equal to 10 percent of its capacity. • Testing  To test the program, try running it with a few samples of input data. One sample should bring the oil level remaining to exactly 10 percent of the capacity. For example, if the capacity is 10,000 gallons, enter a final daily usage amount that brings the oil supply to 1,000 gallons and see what happens.

  25. // File: oilSupply.cpp (p.249, chapter 5) // Displays daily usage and amount left in oil tank. #include <iostream> #include <conio> const float CAPACITY = 10000; // tank capacity const float MINPCT = 10.0; // minimum percent float monitorOil (float, float); int main() { float supply; // input - initial oil supply float oilLeft; // output - oil left in tank float minOil; // minimum oil supply // Get the initial oil supply. cout << "Enter initial oil supply: "; cin >> supply; // Compute the minimum oil supply. minOil = CAPACITY * (MINPCT / 100.0); // Compute and display the amount of oil left each day. oilLeft = monitorOil(supply, minOil); // Display a warning message if supply is less than minimum cout << endl << oilLeft << " gallons left in tank." << endl; if (oilLeft < minOil) cout << "Warning - amount of oil left is below minimum!" << endl; getch(); return 0; } float monitorOil (float supply, float minOil) { // Local data . . . float usage; // input from user - Each day's oil use float oilLeft; // Amount left each day oilLeft = supply; while (oilLeft > minOil) { cout << "Enter amount used today: "; cin >> usage; oilLeft -= usage; cout << "After removal of " << usage << " gallons," << endl; cout << "number of gallons left is " << oilLeft << endl << endl; } return oilLeft; }

  26. 5.5 Loop Design and Loop Patterns • Sentinel-Controlled Loops 1. Read the first data item. 2. while the sentinel value has not been read      3. Process the data item.   4. Read the next data item. • Flag Controlled Loops 1. Set the flag to false. 2. while the flag is false 3. Perform some action. 4. Reset the flag to true if the anticipated event occurred.

  27. Sentinel Loops • A sentinel is a specific predetermined value used to terminate one type of event-controlled loop. • It is the same type as the other extracted data (but not possibly valid data). • For example, the int constant -1 may act as a sentinel when all valid int data > -1

  28. // File: SumScores.cpp (p.255, chapter 5) // Accumulates the sum of exam scores. #include <iostream> #include <conio> void displayGrade(int);// See Listing 4.3 (p.202) int main() { const int SENTINEL= -1; // sentinel value int score; // input - each exam score int sum; // output - sum of scores int count; // output - count of scores int average; // output - average score // Process all exam scores until sentinel is read count = 0; sum = 0; cout << "Enter scores one at a time as requested." << endl; cout << "When done, enter " << SENTINEL << " to stop." << endl; cout << "Enter the first score: "; cin >> score; while (score != SENTINEL) { sum += score; count++; displayGrade(score); cout << endl<< "Enter the next score: "; cin >> score; } cout << endl << endl; cout << "Number of scores processed is " << count << endl; cout << "Sum of exam scores is " << sum << endl; // Compute and display average score. if (count > 0) { average = sum / count; cout << "Average score is " << average; } getch(); return 0; } void displayGrade(int score) { if (score >= 90) cout << "Grade is A" << endl; else if (score >= 80) cout << "Grade is B" << endl; else if (score >= 70) cout << "Grade is C" << endl; else if (score >= 60) cout << "Grade is D" << endl; else cout << "Grade is F" << endl; }

  29. Flag-Controlled Loops // File: Flag_Controlled.cpp #include <iostream> #include <conio.h> using namespace std; char getDigit(); // See Example 4.** int main() { char thisChar; cout << "For demonstrating Flg Controoled example\n"; thisChar = getDigit(); cout << "Character returned is: " << thisChar << endl; getch(); return 0; } //Listing 5.8, p.258 char getDigit() { char nextChar; bool digitRead; digitRead = false; while (!digitRead) { cout << "Please enter a charter: "; cin >> nextChar; digitRead = (('0' <= nextChar) && (nextChar <= '9')); } return nextChar; }

  30. 5.6 The do-while Statement • The do while statement is similar to the while loop, but the do while loop has the test at the end. General form: do { iterative-part } while (loop-test) ; • Notice the iterative part executes BEFORE the loop-test)

  31. When to use the do-while loop • The do while loop is a good choice for obtaining interactive input from menu selections. • Consider a function that won't stop executing until the user enters an N, O, or S: • Post test loop

  32. Example do-while loop //file name: menu_Option.cpp char menuOption() { // POST: Return an upper case 'N', 'O' or 'S' char option; do { cout << "Enter N)ew, O)pen, S)ave: "; cin >> option; option = toupper(option); // from ctype.h } while (!(option == 'N' || option == 'O' || option == 'S')); return option; } Exercise: (5.6) p.24 #1

  33. // FILE: Largest.cpp (p.263, chapter 5) // FINDS THE LARGEST NUMBER IN A SEQUENCE OF INTEGER VALUES #include <iostream> // needed for cin and cout #include<limits>// needed for INT_MIN #include <conio.h> using namespace std; int main () { // Local data ... int itemValue; // each data value int largestSoFar; // largest value so far int minValue; // the smallest integer // Initialize largestSoFar to the smallest integer. minValue = INT_MIN; largestSoFar = minValue; // Save the largest number encountered so far. cout << "Finding the largest value in a sequence: " << endl; do { cout << "Enter an integer or " << minValue << " to stop: "; cin >> itemValue; if (itemValue > largestSoFar) largestSoFar = itemValue; // save new largest number } while(itemValue != minValue); cout << "The largest value entered was " << largestSoFar << endl; getch(); return 0; } Program Output Finding the largest value in a sequence: Enter an integer or -32768 to stop: -999 Enter an integer or -32768 to stop: 500 Enter an integer or -32768 to stop: 100 Enter an integer or -32768 to stop: -32768 The largest value entered was 500

  34. 3. C++ Syntax: do-whilestatement General Form: do { statement_1; statement_2; … } while(logical expression); BONUS 1. Copy textEditor.cpp, rename it to textEditor_Lname_Fname.cpp. 2. Modify it to be a “better” program. • Notes: • a. At least one repetition of loop body must be ensured. • b. You should have a termination criteria for the logical expression within the • do ... while loop. • Example “do ... while” loop: • do • { • cout << "Enter the " << (counter+1) << " score: " ; • cin >> score; • sum += score; • cout << "Score " << (counter+1) <<":" << score << " current sum is: " • << sum << endl; • counter++; • } while(counter < total_number);

  35. 5.7 Review of while, for, and do-while Loops • while - Most commonly used when repetition is not counter controlled; condition test precedes each loop repetition; loop body may not be executed at all • for - Counting loop - When number of repetitions is known ahead of time and can be controlled by a counter; also convenient for loops involving non counting loop control with simple initialization and updates; condition test precedes the execution. • do-while - Convenient when at least one repetition of loop body must be ensured. Post test condition after execution of body.

  36. Control on Repetition: while, for, and do ... while statements • 1. C++ Syntax: while statement • while (logical expression) • { • statement_1; • statement_2; • ... • } • Note: you should have a termination criteria for the logical expression within the while loop. • 2. C++ Syntax: for statement • for (initialization; test expression; update) • { • statement_1; • statement_2; • ... • } • 3. C++ Syntax: do-while statement • do • { • statement_1; • statement_2; • ... • } while (logical expression); • 1. At least one repetition of loop body must be ensured. • 2. You should have a termination criteria for the logical expression within the • do ... while loop.

  37. An example with three repetition loops • 1.while loop • power = 1; • while(power < 1000) • { • cout << power << endl; • power *= 2; • } // end while • 2. for loop • for(power = 1; power < 1000; power *= 2) • cout << power << endl; • 3.do ... whileloop • power = 1; • do • { • cout << power << endl; • power *= 2; • }while(power < 1000);

  38. 5.8 Nested Loops • Possible to nest loops • Loops inside other loops • Start with outer jump to inner loop • Inner loop continues until complete • Back to outer loop and start again • NestLoop.cpp and Multiplication.cpp examples

  39. Nested Logic outer = 1; while(outer <= 3) { inner = 1; // Resets for each iteration of the outer loop while(inner <= outer) { cout << outer << " " << inner << endl; inner = inner + 1; } // End of the nested loop outer = outer + 1; // Increment the outer loop counter } // The end of the outer loop

  40. // FILE: nestedLoops.cpp(Listing 5.13; p.269) // ILLUSTRATES A PAIR OF NESTED FOR LOOPS #include <iostream> #include <iomanip> #include <conio> using namespace std; int main () { // display heading cout << setw(12) << "i" << setw(6) << "j" << endl; for (int i = 0; i < 4; i++) { cout << "Outer" << setw (7) << i << endl; for (int j = 0; j < i; j++) cout << " Inner" << setw (10) << j << endl; } getch(); return 0; } Output: i j Outer 0 Outer 1 Inner 0 Outer 2 Inner 0 Inner 1 Outer 3 Inner 0 Inner 1 Inner 2

  41. // File: Multiplication.cpp #include <iostream> #include <iomanip> #include <conio.h> using namespace std; int main() { // Display table heading cout << " |"; for (int colHead = 0; colHead < 10; colHead++) cout << setw(3) << colHead; cout << endl; cout << " --------------------------------" << endl; // Display table, row-by-row for (int rowVal = 0; rowVal < 10; rowVal++) { cout << setw(3) << rowVal << '|'; for (int colVal = 0; colVal < 10; colVal++) cout << setw(3) << rowVal * colVal; cout << endl; } getch(); return 0; } | 0 1 2 3 4 5 6 7 8 9 -------------------------------- 0| 0 0 0 0 0 0 0 0 0 0 1| 0 1 2 3 4 5 6 7 8 9 2| 0 2 4 6 8 10 12 14 16 18 3| 0 3 6 9 12 15 18 21 24 27 4| 0 4 8 12 16 20 24 28 32 36 5| 0 5 10 15 20 25 30 35 40 45 6| 0 6 12 18 24 30 36 42 48 54 7| 0 7 14 21 28 35 42 49 56 63 8| 0 8 16 24 32 40 48 56 64 72 9| 0 9 18 27 36 45 54 63 72 81

  42. 5.9 Debugging and Testing Programs • Modern Integrated Development Environments (IDEs) include features to help you debug a program while it is executing. • If you cannot use a debugger, insert extra diagnostic output statements to display intermediate results at critical points in your program.

  43. 5.10 Common Programming Errors • Coding style and use of braces. • Infinite loops will “hang you up !!” • Use lots of comments before and after a loop. • Test various conditions of loops. • Add white space between code segments using loops. • Initialize looping variables or use internal loop control variables (lcv) in the for loop.

  44. HW#6: Computing Average and Standard Deviation The standard deviation is defined to be the square root of the four values divided by 3: (si-a)2 where a is average of the four scores s1, s2, s3, s4. You must use a function to computer the standard deviation #include <cmath> #include <conio.h> system(“CLS”);

More Related