Repetition and Loop Statements Chapter 5 Why iterate
- Slides: 57
Repetition and Loop Statements Chapter 5
Why iterate? t t t 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. 2
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. 3
5. 1 Counting Loops and the while Statement – General form of the while statement: while ( loop-test ) { iterative-part } – 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 4
Collections of statements are delimited with { and } t while there is another number, do the following { cout << "Enter number: "; cin >> number; sum = sum + number; } average = sum / 100; 5
Flowchart view of while loop False count. Emp < 7 True Get data Compute pay Iterative Part Display pay Inc count. Emp by 1 6
Infinite loops – Infinite loop: a loop that never terminates. – Infinite loops are usually not desirable. – Here is an example of an infinite loop: 7
Infinite loops 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. 8
5. 2 Accumulating a Sum or Product in a Loop t t t Lets look at the idea of adding together a group of numbers Many lines of the same statements Sample code using loop 9
Sum 100 values the hard 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; 10
Sum 100 values the hard way /* . . . 291 statements deleted. . . */ cout << "Enter number: "; cin >> number; sum = sum + number; average = sum / 100; 11
Compute. Pay. cpp // FILE: Compute. Pay. cpp // COMPUTES THE PAYROLL FOR A COMPANY #include <iostream> #include "money. h" int main () { int number. Emp; int count. Emp; float hours; money rate; money pay; money total. Pay; 12
Compute. Pay. cpp // Get number of employees from user. cout << "Enter number of employees: "; cin >> number. Emp; // Compute each employee's pay and add it to // the payroll. total. Pay = 0. 0; count. Emp = 0; 13
Compute. Pay. cpp while (count. Emp < number. Emp) { cout << "Hours: "; cin >> hours; cout << "Rate : $"; cin >> rate; pay = hours * rate; cout << "Pay is " << pay << endl; total. Pay += pay; count. Emp++; } 14
Compute. Pay. cpp cout << "Total payroll is " << total. Pay << endl; cout << "All employees processed. " << endl; return 0; } 15
Compute. Pay. 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 All employees processed. 16
Compound Assignment Operators t t Lets look at the idea of adding together a group of numbers Short hand notation total. Pay += pay; – same as total. Pay = total. Pay + pay; t See Table 5. 2 17
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. 18
Example for loop – This is a for-loop version of a countercontrolled loop : – Scope of the loop control variable: for(int counter = 1; counter<=5; counter = counter+1) { } cout << counter << " "; • Output: ________________? 19
General form of a for loop for( initial statement ; loop-test ; repeated statement) { iterative-part } – When a for loop is encountered, the initialstatement 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. 20
Flowchart for a for loop Initial statement False True count. Emp < 7 Get Data Compute Pay Display Pay Increase count. Emp by 1 21
Other Incrementing Operators t 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 t t 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 t In many programming situations, you will not be able to determine the exact number of loop repetitions t 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 t Case Study: Monitoring Oil Supply – Problem We 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 display the amount left in the tank at the end of each day and 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
Oil. Supply. cpp // File: oil. Supply. cpp // Displays daily usage and amount left in oil tank. #include <iostream> using namespace std; const float CAPACITY = 10000; // tank capacity const float MINPCT = 10. 0; // minimum percent float monitor. Oil(float, float); 26
Oil. Supply. cpp int main() { float supply; // input - initial oil supply float oil. Left; // output - oil left in tank float min. Oil; // minimum oil supply // Get the initial oil supply. cout << "Enter initial oil supply: "; cin >> supply; 27
Oil. Supply. cpp // Compute the minimum oil supply. min. Oil = CAPACITY * (MINPCT / 100. 0); // Compute and display the amount of oil // left each day. oil. Left = monitor. Oil(supply, min. Oil); // Display a warning message if supply is less // than minimum cout << endl << oil. Left << " gallons left in tank. " << endl; 28
Oil. Supply. cpp if (oil. Left < min. Oil) cout << "Warning - amount of oil left is below minimum!" << endl; return 0; } 29
Oil. Supply. cpp float monitor. Oil(float supply, float min. Oil) { // Local data. . . float usage; // input from user - Each day's oil use float oil. Left; // Amount left each day oil. Left = supply; while (oil. Left > min. Oil) { cout << "Enter amount used today: "; cin >> usage; oil. Left -= usage; 30
Oil. Supply. cpp cout << "After removal of " << usage << " gallons, " << endl; cout << "number of gallons left is " << oil. Left << endl; } return oil. Left; } 31
5. 5 Loop Design and Loop Patterns t 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. t 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. 32
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 33
Sum. Scores. cpp // File: Sum. Scores. cpp // Accumulates the sum of exam scores. #include <iostream> using namespace std; void display. Grade(int); int main() { 34
Sum. Scores. cpp const int SENTINEL = -1; int score; int sum; int count; int average; // 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; 35
Sum. Scores. cpp cout << "Enter the first score: "; cin >> score; while (score != SENTINEL) { sum += score; count++; display. Grade(score); cout << endl<< "Enter the next score: "; cin >> score; } 36
Sum. Scores. cpp cout << 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; } Return 0; } 37
Sum. Scores. cpp void display. Grade (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; } 38
Sum. Scores. cpp Program Output w/ intended error! Enter the scores one at a time as requested. When done, enter -1 to stop. Enter the first score: 55 Enter the next score: 33 Enter the next score: 77 Enter the next score: -1 Sum of exam scores is 165 3 exam scores were processed. Average of the exam scores is 55. 0 39
Flag-Controlled Loops char get. Digit() { char next. Char; bool digit. Read; digit. Read = false; while (!digit. Read) { cin >> next. Char; digit. Read = (('0' <= next. Char) && (next. Char <= '9')); } return next. Char; } 40
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) 41
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 42
Example do-while loop char menu. Option() { // 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; } 43
Largest. cpp // FILE: Largest. cpp // FINDS THE LARGEST NUMBER IN A SEQUENCE OF // INTEGER VALUES #include <iostream> #include <limits> // needed for cin and cout // needed for INT_MIN using namespace std; int main () { 44
Largest. cpp // Local data. . . int item. Value; // each data value int largest. So. Far; // largest value so far int const min. Value = -32768; // exit cond. // Initialize largest. So. Far to the smallest // integer. min. Value = INT_MIN; largest. So. Far = min. Value; 45
Largest. cpp // Save the largest number encountered so far. cout << "Finding the largest value in a sequence: " << endl; do { cout << "Enter an integer or " << min. Value << " to stop: "; cin >> item. Value; if (item. Value > largest. So. Far) largest. So. Far = item. Value; } while (item. Value != min. Value); 46
Largest. cpp cout << "The largest value entered was " << largest. So. Far << endl; return 0; } 47
Largest. cpp 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 48
5. 7 Review of while, for, and do-while Loops t t 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. 49
Review of while, for, and dowhile Loops t do-while - Convenient when at least one repetition of loop body must be ensured. Post test condition after execution of body. 50
5. 8 Nested Loops t 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 t Nest. Loop. cpp and Triangle. cpp examples 51
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 52
Nested. Loops. cpp // FILE: Nested. Loops. cpp // ILLUSTRATES A PAIR OF NESTED FOR LOOPS #include <iostream> #include <iomanip> int main () { // display heading cout << setw(12) << "i" << setw(6) << "j" << endl; 53
Nested. Loops. cpp 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; } return 0; } 54
Nested. Loops. cpp Program Output Outer Inner Inner i 0 1 j 0 2 0 1 3 0 1 2 55
5. 9 Debugging and Testing Programs t t 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. 56
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. 57
- Automatic counter loop flowchart
- To iterate is human to recurse divine
- Iterate
- Iterate through cell array matlab
- Pictures
- Selection and repetition
- Bandwagon picture examples
- Contoh open loop system
- Fifth gear loop the loop
- Open loop vs closed loop in cars
- Manakah yang lebih baik open loop atau close loop system
- Statement while... wend digunakan untuk
- Fingerprint basics
- Multi loop pid controller regolatore pid multi loop
- Repetition statement
- Don't ask why why why
- Why do desert animals have longer loop of henle
- Why do desert animals have longer loop of henle
- Financial statements and ratio analysis chapter 3
- How to improve current ratio
- Chapter 2 financial statements taxes and cash flow
- Great gatsby ch3 summary
- The great gatsby summary chapter 3
- The expense recognition principle aims to record
- Sole proprietorship income statement
- Chapter 7 financial statements for a proprietorship
- Chapter 3 adjusting accounts for financial statements
- Intercompany bond transactions
- Chapter 4 analysis of financial statements
- Chapter 4 analysis of financial statements
- Working with financial statements chapter 3
- Chapter 3 adjusting accounts for financial statements
- Chapter 3 adjusting accounts for financial statements
- Why-why analysis
- Why do you cry, willie
- Does the table represent a function why or why not
- Does the table represent a function why or why not
- Why or why not
- Contoh root cause analysis
- Why study financial institutions
- Painted faces and long hair meaning
- Examples of aliteration
- Repetition examples sentences
- What is the difference between replication and repetition
- Principle of repetition
- Characteristics of fixed poetry
- What is multigrade
- Alliteration example in romeo and juliet
- Conceit literary device
- Types of poems
- The repetition of the same letter or sound
- Consonance and alliteration
- Difference between consonance and assonance
- Repetition method and reiteration method
- Repetition method in surveying
- What is alliteration and repetition
- Repetition and emphasis
- Repetition method in theodolite surveying