1 / 83

Starting Out with C++ Early Objects Seventh Edition

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

parkerjanet
Download Presentation

Starting Out with C++ Early Objects Seventh Edition

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: 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

  2. 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

  3. 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

  4. STOP / START HERE Chapter 5 Repetition / Loops Increment/Decrement

  5. 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

  6. 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.

  7. 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

  8. 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.

  9. 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

  10. 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.

  11. STOP / START HERE Chapter 5 Repetition / Loops for Loop (based on counting / sequence)

  12. STOP / START HERE Chapter 5 – LOOPING Repetition

  13. 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 )

  14. Syntax / Format No ; goes here for(initialization;continuation_test;update) { body; }

  15. for Loop Mechanics

  16. for Loop Flow of Control initialization code update code false test true statement(s)

  17. for Loop Example (Tracing) int sum = 0, num; for (num = 1; num <= 6; num++) sum += num; cout << "Sum of 1–6 is “ << sum << endl;

  18. 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.

  19. 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;

  20. STOP / START HERE Chapter 5 Repetition / Loops part 3 - while Loop (indefinite repetition)

  21. false condition true statement(s) while Loop Flow of Control

  22. 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

  23. while Loop Example int val = 5; while (val >= 0) { cout << val << " "; val--; } produces output: 5 4 3 2 1 0 • Execution Trace

  24. 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

  25. 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

  26. 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.

  27. 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 { … }

  28. Constructing Continuation Condition from Stopping Condition

  29. STOP / START HERE Chapter 5 Repetition / Loops part 4 - while Loop (repetition patterns)

  30. 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

  31. 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 ...

  32. 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

  33. 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

  34. 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 ...

  35. 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

  36. 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

  37. 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

  38. 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. ...

  39. 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

  40. STOP / START HERE Chapter 5 Repetition / Loops part 5 - Loop processing patterns

  41. 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.

  42. 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(…) )

  43. 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; }

  44. 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++; }

  45. 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.

  46. 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; }

  47. 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; }

  48. 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? }

  49. 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; }

  50. STOP / START HERE Chapter 5 Repetition / Loops part 6 - do-while Loop (repeat … test)

More Related