Presentation is loading. Please wait.

Presentation is loading. Please wait.

Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy.

Similar presentations


Presentation on theme: "Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy."— Presentation transcript:

1 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Revised 2015 E.L. Jones, Ph.D., FAMU Chapter 5: Looping

2 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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 5-2

3 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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 5-3

4 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STOP / START HERE Chapter 5 Repetition / Loops Increment/Decrement 8-4

5 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley A. Some New Operators Increment and Decrement ++ adds one to a variable val++; is the same as val = val + 1; -- subtracts one from a variable val--; is the same as val = val – 1; can be used in prefix mode (before) or postfix mode (after) a variable 5-5

6 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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. 5-6

7 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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 5-7

8 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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 old value of the variable is returned … and The new value of the variable is available beyond this point in the expression/statement. 5-8

9 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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 5-9

10 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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. 5-10

11 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STOP / START HERE Chapter 5 Repetition / Loops for Loop (based on counting / sequence) 8-11

12 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STOP / START HERE Chapter 5 – LOOPING Repetition 8-12

13 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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 ) 5-13

14 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Syntax / Format for(initialization ; continuation_test ; update) { body; } 5-14 No ; goes here

15 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley for Loop Mechanics 5-15

16 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley for Loop Flow of Control 5-16 true statement(s) false test initialization code update code

17 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley for Loop Example (Tracing) int sum = 0, num; for (num = 1; num <= 6; num++) sum += num; cout << "Sum of 1–6 is “ << sum << endl; 5-17 Step -1234567 num (before) ?1234567 condition-TTTTTTF sum0136101521 num (after) -234567

18 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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. 5-18

19 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley for Loop 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; 5-19

20 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STOP / START HERE Chapter 5 Repetition / Loops part 3 - while Loop (indefinite repetition) 8-20

21 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley while Loop Flow of Control 5-21 true statement(s) false condition

22 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley How the while 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 5-22

23 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley while Loop Example int val = 5; while (val >= 0) { cout << val << " "; val--; }  produces output: 5 4 3 2 1 0 Execution Trace 5-23 Step 1234567 val (before) 543210 conditionTTTTTTF output543210 val (after) 43210

24 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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 5-24

25 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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 5-25

26 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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. 5-26

27 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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 { … } 5-27

28 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Constructing Continuation Condition from Stopping Condition 5-28 Stopping ConditionContinuation Condition = NOT stopping X > 5X 5) ] X <= 5X > 5 [ (NOT X<= 5) ] X != 4X == 4 X>5 or Y == 2X 5) and NOT (Y==2) ] M outside (1,9]M>1 && M<=9 [ Inside (1,9] ] Q inside [5,18)Q =18 [ Outside [5,18) ] Failed cin operation! cin.fail() [ non-failure ] Failed read into variables a,b,c from stream inF (inF >> a >> b >> c) [Successful read] x is odd and y is evenx is even or y is odd (x % 2 == 0) || (y%2 ==1)

29 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STOP / START HERE Chapter 5 Repetition / Loops part 4 - while Loop (repetition patterns) 8-29

30 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Repetition Pattern: READ-CHECK-USE Data-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 5-30

31 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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... 5-31

32 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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 5-32

33 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Repetition Pattern: READ-CHECK-USE Input 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 5-33

34 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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... 5-34

35 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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 5-35

36 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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 5-36

37 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Repetition Pattern: CHECK-READ-USE Result-Driven Goal: Sum input values until sum exceeds Limit. Input design: List of input values, no sentinel. Sample Problem: Limit = 17. Inputs: 5 3 7 4 8 7 Expected Outputs: 19 5-37

38 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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.... 5-38

39 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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 5-39

40 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STOP / START HERE Chapter 5 Repetition / Loops part 5 - Loop processing patterns 8-40

41 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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. 5-41

42 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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(…) ) 5-42

43 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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; } 5-43

44 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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++; } 5-44

45 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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. 5-45

46 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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; } 5-46

47 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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; } 5-47

48 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 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? } 5-48

49 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Example: Minimum Input Value Accumulator 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; } 5-49

50 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STOP / START HERE Chapter 5 Repetition / Loops part 6 - do-while Loop (repeat … test) 8-50

51 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley do-while Flow of Control 5-51 statement(s) condition false true

52 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The do-while Loop do-while : a post test loop ( condition is evaluated after the loop executes) Format: do { loop_body } while (condition); 5-52 Notice the required ;

53 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley do-while Loop Notes Loop always executes at least once Execution continues as long as condition is true ; the loop is exited when condition becomes false Two major uses: –Input validation –Menu-driven programs 5-53

54 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Data Validation Pattern READ-CHECK Rationale: Avoid garbage-in, garbage-out (GIGO) by confirming validity of inputs. 1.Prompt for and read input data. 2.Check the data for validity. 3.If data value is invalid –Display error message –Goto step 1. 4.Process the input data value. 5-54

55 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Repetition Pattern: READ-CHECK Data-Driven ALGORITHM: Valid means num < 15 (Limit) Read num. // READ. if (num is not valid) // CHECK. Read num. // READ. if (num is not valid) Read num.... // Use valid value 5-55

56 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Validation Pattern: READ-CHECK Validation ALGORITHM implemented as a do-while loop: int num; // Must be < 15. do { cin >> num; // READ. } while (num >= 15); // CHECK (for invalid).... // Rest of program. Pattern: R-C R-C … C 5-56

57 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Repetition Pattern: READ-CHECK Validation ALGORITHM implemented as while loop (not advised): int num; cin >> num; // READ. while (num >= Limit) // CHECK. { cin >> num; // READ. }... // Rest of program. Pattern: R-C R-C … C 5-57

58 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Input Validation using the do-while Loop do { cout << "Enter a number (1-100) and" << " I will guess it. "; cin >> number; } while (number 100);//Invalid. // … Code to use the valid number goes here. 5-58

59 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Input Validation: while Loop Example cout << "Enter a number (1-100) and" << " I will guess it. "; cin >> number; while (number 100)//outside range { cout << "Number must be between 1 and 100." << " Re-enter your number. "; cin >> number; } // … Code to use the valid number goes here. 5-59

60 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Menu-Driven Program Suppose menu choice to QUIT is char ‘Q’. PATTERN: do { //-| Display menu and read choice. //-| Perform menu choice. switch (choice) {... }//switch } while (choice != ‘Q’); 5-60

61 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STOP / START HERE Chapter 5 Repetition / Loops part 7 – Nested loops (2-dimensional patterns) 8-61

62 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5.10 Deciding Which Loop to Use while : pretest loop (Not sure how many repetitions, possibly zero) –Patterns: Read-Check-Use, Check-Use do-while : post test loop (must execute body at least once, e.g., menu-driven) Patterns: Read-Check, Use-Check for : pretest loop (counter or sequence controlled loop) 5-62

63 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley A 1-Dimensional Problem Produce output: 1 2 3 4 5 What’s required: produce ONE line containing 1 2 3 4 5 Observe: output is displayed in ONE direction, horizontally Solution: produce sequence 1-5 Code: (call it 1LINE) for (num = 1; num <= 5; num++) cout << num << ‘ ‘; cout << endl; 5-63

64 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley A 2-Dimensional Problem Produce output: 1 2 3 4 5 1 2 3 4 5 What’s required: produce 5 lines containing 1 2 3 4 5 Root problem: produce ONE line containing 1 2 3 4 5 Repetition: Repeat root problem 5 times Code: for (line=1; line <= 5; line++) //1LINE 5-64

65 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Solution to 2-Dimensional Problem Produce output: 1 2 3 4 5 1 2 3 4 5 for (line=1; line <= 5; line++) //vertical { } 5-65

66 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Solution to 2-Dimensional Problem Produce output: 1 2 3 4 5 1 2 3 4 5 for (line=1; line <= 5; line++) //vertical { for (num = 1; num <= 5; num++) //horizontal cout << num << ‘ ‘; cout << endl; } 5-66

67 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Nested Loops A nested loop is a loop inside the body of another loop Example: for (row = 1; row <= 3; row++) { for (col = 1; col <= 3; col++) { cout << row * col << endl; } //inner } //outer 5-67 outer loop inner loop

68 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Nested Loops A nested loop is a loop inside body of another loop Example: for (row = 1; row <= 3; row++) //outer loop { for (col = 1; col <= 4 ; col++) //inner loop { cout << row << col << ‘ ‘; } cout << endl; } Outputs: 11 12 13 14 (output when row is 1) 21 22 23 24(output when row is 2) 31 32 33 34 5-68

69 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Nested Loops 10 students, each with 4 test scores. Compute average for each student. ALGORITHM: Repeat 10 times for (int count=1;count<=10;count++) { Sum = 0.0; Repeat 4 times for (int s=1;s<=4;s++) Sum = 0 { Read score cin >> score; Add score to Sum Sum += score; } //inner loop. Calculate avg = Sum / 4 avg = Sum/4; Display average cout << avg << endl; } // outer loop. 5-69

70 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Notes on Nested Loops Inner loop goes through all its repetitions for each repetition of outer loop Inner loop repetitions complete sooner than outer loop Total number of repetitions for inner loop is sum of the number of repetitions for each repetition of the outer loop. In previous example, inner loop repeats 4+4+4 = 12 times 5-70

71 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STOP / START HERE Chapter 5 Repetition / Loops part 7b – Nested loops (coding examples) 8-71

72 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Coding - Nested Loop 1 Produce output: 1 2 3 4 5 1 2 3 4 5 What’s required: produce 5 lines containing 1 2 3 4 5 Root problem: produce ONE line containing 1 2 3 4 5 Repetition: Repeat root problem 5 times. 5-72

73 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Coding - Nested Loop 2 Produce output: 1 2 3 4 5 2 3 4 5 3 4 5 4 5 5 What’s required: produce 5 lines of output, each line starting with the line number Root problem: produce ONE line starting at a specific value and counting by 1 up to 5 Repetition: Repeat root problem 5 times. 5-73

74 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Coding - Nested Loop 3 Produce output: 5 4 3 2 1 4 3 2 1 3 2 1 2 1 1 What’s required: produce 5 lines of output showing a decreasing sequence, each line starting with a lower number than the previous line. Root problem: produce ONE line starting at a specific value and counting backwards by 1 down to 1 Repetition: Repeat root problem 5 times. 5-74

75 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Coding - Nested Loop 4 Inputs: 3 Output: 80 90 100 -1 avg = 90 -1 avg = 0 80 80 80 -1 avg = 80 Required: Read #students, then compute average test score, where test scores are terminated by sentinel -1. Root problem: Calculate average score for ONE student based on input design (sentinel -1). Repetition: Repeat root problem for each student. 5-75

76 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley STOP / START HERE Chapter 5 Repetition / Loops part 7 – Nested loops (2-dimensional patterns) 8-76

77 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Revised 2015 E.L. Jones, Ph.D., FAMU Chapter 5: Looping

78 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley More for Loop Modifications (These are NOT Recommended) Can omit initialization if already done int sum = 0, num = 1; for (; num <= 10; num++) sum += num; Can omit update if done in loop for (sum = 0, num = 1; num <= 10;) sum += num++; Can omit test – may cause an infinite loop for (sum = 0, num = 1; ; num++) sum += num; Can omit loop body if all work is done in header 5-78

79 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Using read failure to Test for the End of a File instream >> value -- returns false when not successful Example: while (datafile >> score) { sum += score; datafile >> score; } 5-79

80 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Using the eof() Function to Test for the End of a File instream.eof() member function returns true when the previous read encountered the end of file. Example: datafile >> score; while (!datafile.eof()) { sum += score; datafile >> score; } 5-80

81 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Problems Using eof() For the eof() function to work correctly using this method, there must be a whitespace (space, tab, or [Enter] ) between the last data value and the EOF marker. InBuffer: 33 33 is read but ! eof() Otherwise the eof() will be set when reading the final data value; this value will not be processed. when InBuffer: 33, 33 is read but eof() true. But after the extraction, the buffer contains only whitespace (but is not exposed, so eof() is false, and there appears to be data in InBuffer. InBuffer: 5-81

82 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5.13 The continue Statement Can use continue to go to end of loop body and prepare for next repetition – while and do-while loops go to test and repeat the loop if test condition is true – for loop goes to update step, then tests, and repeats loop if test condition is true Use sparingly – like break, can make program logic hard to follow 5-82

83 Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 5.14 Creating Good Test Data Program should work under different conditions –normal situations –Extreme conditions near the limits of valid inputs –invalid input Quality of test data vs quantity Data should force loops/decisions to achieve all possible outcomes 5-83


Download ppt "Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy."

Similar presentations


Ads by Google