830 likes | 844 Views
Chapter 5: Looping. Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Revised 2015 E.L. Jones, Ph.D., FAMU. Topics. 5.1 The Increment and Decrement Operators 5.2 Introduction to Loops: The while Loop
E N D
Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Revised 2015 E.L. Jones, Ph.D., FAMU
Topics 5.1 The Increment and Decrement Operators 5.2 Introduction to Loops: The while Loop 5.3 Using the while loop for Input Validation 5.4 Counters 5.5 The do-while loop 5.6 The for loop 5.7 Keeping a Running Total
Topics (continued) 5.8 Sentinels 5.9 Using a Loop to Read Data From a File 5.10 Deciding Which Loop to Use 5.11 Nested Loops 5.12 Breaking Out of a Loop 5.13 The continue Statement 5.14 Creating Good Test Data
STOP / START HERE Chapter 5 Repetition / Loops Increment/Decrement
A. Some New OperatorsIncrement and Decrement • ++ adds one to a variable val++;is the same as val= val + 1; • -- subtracts one from a variable val--;is the same asval = val – 1; • can be used in prefix mode (before) or postfix mode (after) a variable
Prefix Mode • ++val and --val increment/decrement the variable, then return the new value of the variable. * int k = 3, m = 5; cout << k << “ “ << ++k << “ “ << k << endl; cout << m << “ “ << --m << “ “ << --m << endl; • The new value of the variable is available from that point in the expression/statement.
Prefix Mode Example int x = 1, y = 1; x = ++y; // y is incremented to 2 // Then 2 is assigned to x cout << x << " " << y; // Displays 2 2 x = --y; // y is decremented to 1 // Then 1 is assigned to x cout << x << " " << y; // Displays 1 1
Postfix Mode • val++ and val-- return the old value of the variable, then increment or decrement the variable * int k = 3, m = 5; cout << k++ << “ “ << k << “ “ << ++k << endl; cout << m-- << “ “ << m << “ “ << --m << endl; • The oldvalue of the variable is returned … and • The new value of the variable is available beyond this point in the expression/statement.
Postfix Mode Example int x = 1, y = 1; x = y++; // y++ returns a 1 // The 1 is assigned to x // and y is incremented to 2 cout << x << " " << y; // Displays 1 2 x = y--; // y-- returns a 2 // The 2 is assigned to x // and y is decremented to 1 cout << x << " " << y; // Displays 2 1
Increment & Decrement Notes • These operators CHANGE the value of a variable • The operand must be a variable • Can be used in arithmetic expressions result = num1++ + --num2; result=(num1+num2)++; //Illegal.WHY? • Can be used in relational expressions if (++num > limit) // Comparisons are if (num++ > limit) // different.
STOP / START HERE Chapter 5 Repetition / Loops for Loop (based on counting / sequence)
STOP / START HERE Chapter 5 – LOOPING Repetition
B. The for Loop • Loop based on counting • Example: int count; for (count = 1; count <= 10; count++) cout << count << “ “; cout << endl; • Output: 1 2 3 4 5 6 7 8 9 10 • What about: for ( count = 5; count <= 40; count+=5 )
Syntax / Format No ; goes here for(initialization;continuation_test;update) { body; }
for Loop Flow of Control initialization code update code false test true statement(s)
for Loop Example (Tracing) int sum = 0, num; for (num = 1; num <= 6; num++) sum += num; cout << "Sum of 1–6 is “ << sum << endl;
for Loop Notes If contination_condition is false the first time it is evaluated, the body of the loop will not be executed The update expression can modify the control variable by any amount (commonly ++, --, +=, -=, *=, /=, %= ) The loop control variable should not be modified in the body of the loop.
forLoop Modifications • Can define variables in initialization code • Their scope is the for loop • Initialization and update code can contain more than one statement • Separate statements with commas, not semicolons • Example: for (int sum = 0, num = 1; num <= 10; num++) sum += num;
STOP / START HERE Chapter 5 Repetition / Loops part 3 - while Loop (indefinite repetition)
false condition true statement(s) while Loop Flow of Control
How thewhile Loop Works while (condition) { loop_body } condition is evaluated • if it is true, the body is executed, and then condition is evaluated again • if it is false, the loop is exited
while Loop Example int val = 5; while (val >= 0) { cout << val << " "; val--; } produces output: 5 4 3 2 1 0 • Execution Trace
The while Loop • Programming construct to execute certain statements repeatedly (>= 0 times) • while loop format: while (condition) { loop_body statement(s); } • The {} can be omitted if there is only one statement in the body of the loop
while Loop is a Pretest Loop while is a pretest loop (condition is evaluated before the loop executes) If the condition is initially false, the statement(s) in the body of the loop are never executed If the condition is initially true, the statement(s) in the body continue to be executed until the condition eventually becomes false
Exiting (terminating) the Loop • The loop body must contain code to force the condition to eventually become false,so the loop can be exited • Otherwise, you have an infinite loop (i.e., a loop that does not stop) • Example of an infinite loop: x = 5; while (x > 0) // Infinite loop: NOTHING cout << x; // x NOT CHANGED from 5.
Common Loop Errors • Don’t forget the { } : int numEntries = 1; while (numEntries <=3) cout << "Still working … "; numEntries++; // not in the loop body • Don’t use = when you mean to use == while (numEntries = 3) // always true { cout << "working … "; numEntries++; } while (numEntries = 0) // always false { … }
STOP / START HERE Chapter 5 Repetition / Loops part 4 - while Loop (repetition patterns)
Repetition Pattern: READ-CHECK-USEData-Driven Goal: Read and process input till end of data. Input design: List of values that ends with a special value called a SENTINEL that represents “END OF DATA”. Sample Problem: Read and display input values. Input design: input values terminated by -999. Inputs: 5 9 4 8 7 -999 Expected Outputs: 5 9 4 8 7
Repetition Pattern: READ-CHECK-USE ALGORITHM: Read num. // READ. if (num is not SENTINEL) // CHECK. process num. // USE. Read num. if (num is not SENTINEL) process num ...
Repetition Pattern: READ-CHECK-USE ALGORITHM implemented as while loop: cin >> num; // READ. while (num != -999) // CHECK. { cout << num << “ “; // USE. cin >> num; // READ. } . . . // Rest of program. Pattern: R-C-U R-C-U … R-C
Repetition Pattern: READ-CHECK-USEInput File-Driven Goal: Read and process input file till end of data. Input design: No special values in file. Sample Problem: Read and display values in file. Input file contains: 5 9 4 8 7 Expected Outputs: 5 9 4 8 7
Repetition Pattern: READ-CHECK-USE (input file) ALGORITHM: Read num. // READ. if (read successful) // CHECK. process num. // USE. Read num. if (read successful) process num ...
Repetition Pattern: READ-CHECK-USE(input file) ALGORITHM implemented as while loop: ifstream inF(“filename”); while ( inF >> num ) // READ + CHECK. { cout << num << “ “; // USE. } . . . // Rest of program. Pattern: R-C-U R-C-U … R-C
Repetition Pattern: READ-CHECK-USE(input file – eof() function) ALGORITHM implemented as while loop with eof(): ifstream inF(“filename); inF >> num; // READ. while ( ! inF.eof() ) // CHECK. { cout << num << “ “; // USE. inF >> num; // READ. } . . . // Rest of program. Pattern: R-C-U R-C-U … R-C
Repetition Pattern: CHECK-READ-USEResult-Driven Goal: Sum input values until sum exceeds Limit. Input design: List of input values, no sentinel. Sample Problem: Limit = 17. Inputs: 5374 8 7 Expected Outputs: 19
Repetition Pattern: CHECK-READ-USE ALGORITHM: sum = 0 if (sum <= Limit) // CHECK. Read num. // READ Process num. // USE. if (sum <= Limit) Read num. Process num. ...
Repetition Pattern: CHECK-READ-USE ALGORITHM implemented as while loop: int num, Limit, sum = 0; while (sum <= Limit) // CHECK. { cin >> num; // READ. sum += num; // USE. } . . . // Rest of program. Pattern: C-R-U C-R-U … C
STOP / START HERE Chapter 5 Repetition / Loops part 5 - Loop processing patterns
Enabling the User to Control Repetition (A) User can specify the sentinel value marking the end of inputs. (B) User can specify number of input values. The control data must be the first input read, prior to reading the data values.
Count Driven Processing Counter: variable that is incremented or decremented each time a loop repeats Can be used to control execution of the loop (loop control variable) Must be initialized before entering loop Must be updated in the loop body or loop header (e.g., for(…) / while(…) )
Example: User Controls Repetition(for loop preferred) int num, limit; cout << "How many entries in table? "; cin >> limit; cout << "Table of squares\n"; cout << “number square\n"; for (num=1; num <= limit; num++) { cout << setw(5) << num << setw(6) << num*num << endl; }
Example: User Controls Repetition(equivalent while loop – not advised) int num, limit; cout << "Table of squares\n"; cout << "How high to go? "; cin >> limit; cout << “number square\n"; num = 1; while (num <= limit) { cout << setw(5) << num << setw(6) << num*num << endl; num++; }
Desired Result: Accumulators • Accumulator: variable that updated each time a loop repeats • “answer, so far” • Running totals • Other running results computed using +=, -=, *=, /= or %= • Additive accumulator initialized to 0 • Multiplicative accumulators initialized by 1.
Example: Sum of N Input Values int numValues, count, num, sum; cout << “Enter #values to add: “; cin >> numValues; sum = 0; // Accumulator must begin at 0. for (count=1; count <= numValues; count++) { cin >> num; sum += num; }
Example: Product of N Input Values int numValues, count, num, product; cout << “Enter #values to multiply: “; cin >> numValues; product = 1; // Accumulator must begin at 1. for (count=1; count <= numValues; count++) { cin >> num; product *= num; }
Example: Sums of Negative and Positive Input Values int numValues, count, num; int sumPos, sumNeg; // 2 Accumulators. cout << “Enter #input values: “; cin >> numValues; sumPos = sumNeg = 0; // Accum’s begin at 0. for (count=1; count <= numValues; count++) { cin >> num; if (num > 0) sumPos += num; else if (num < 0) sumNeg += num; // WHY? }
Example: Minimum Input ValueAccumulator is … “minimum, so far” int numValues, count, num; int minVal; // Accumulator. cout << “Enter #input values: “; cin >> numValues; //?? Initial value of minVal? Best to use 1st value. cin >> minVal; for (count=2; count <= numValues; count++) { cin >> num; if (num < minVal) minVal = num; }
STOP / START HERE Chapter 5 Repetition / Loops part 6 - do-while Loop (repeat … test)