Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition

Similar presentations


Presentation on theme: "Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition"— 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 Chapter 5 Repetition / Loops Increment/Decrement
STOP / START HERE Chapter 5 Repetition / Loops Increment/Decrement See pr8-09.cpp

5 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 See pr5-01.cpp

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 << " " << 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 old value 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 x = y++; // y++ returns a 1 cout << x
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 << " " << y; // Displays 2 1 See pr5-02.cpp

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 = num num2; result = (num1 + num2)++; //Illegal.WHY? Can be used in relational expressions if (++num > limit) // Comparisons are if (num++ > limit) // different.

11 (based on counting / sequence)
STOP / START HERE Chapter 5 Repetition / Loops for Loop (based on counting / sequence) See pr8-09.cpp

12 Chapter 5 – LOOPING Repetition
STOP / START HERE Chapter 5 – LOOPING Repetition See pr8-09.cpp

13 B. The for Loop Loop based on counting Example: int count;
for (count = 1; count <= 10; count++) cout << count << “ “; cout << endl; Output: What about: for ( count = 5; count <= 40; count+=5 )

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

15 for Loop Mechanics

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

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; Step - 1 2 3 4 5 6 7 num (before) ? condition T F sum 10 15 21 num (after) See pr5-09.cpp

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

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

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

22 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

23 while Loop Example Execution Trace int val = 5; while (val >= 0)
{ cout << val << " "; val--; } produces output: Execution Trace Step 1 2 3 4 5 6 7 val (before) -1 condition T F output val (after) See pr5-03.cpp

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
Continuation Condition = NOT stopping X > 5 X <= [ (NOT X>5) ] X <= 5 X > [ (NOT X<= 5) ] X != 4 X == 4 X>5 or Y == 2 X<=5 && Y!=2 [ NOT (X>5) and NOT (Y==2) ] M outside (1,9] M>1 && M<=9 [ Inside (1,9] ] Q inside [5,18) Q<5 || Q>= [ 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 even x is even or y is odd (x % 2 == 0) || (y%2 ==1)

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

30 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 Inputs: Expected Outputs:

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

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-USE Result-Driven
Goal: Sum input values until sum exceeds Limit. Input design: List of input values, no sentinel. Sample Problem: Limit = 17. Inputs: 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 Chapter 5 Repetition / Loops part 5 - Loop processing patterns
STOP / START HERE Chapter 5 Repetition / Loops part 5 - Loop processing patterns See pr8-09.cpp

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(…) ) See pr5-05.cpp

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; } See pr5-06.cpp

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++; } See pr5-06.cpp

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. See pr5-05.cpp

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; } See pr5-06.cpp

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; } See pr5-06.cpp

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? } See pr5-06.cpp

49 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; } See pr5-06.cpp

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

51 do-while Flow of Control
statement(s) condition false true See pr5-07.cpp

52 The do-while Loop do-while: a post test loop (condition is evaluated after the loop executes) Format: do { loop_body } while (condition); Notice the required ;

53 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 See pr5-08.cpp

54 Data Validation Pattern READ-CHECK
Rationale: Avoid garbage-in, garbage-out (GIGO) by confirming validity of inputs. Prompt for and read input data. Check the data for validity. If data value is invalid Display error message Goto step 1. Process the input data value. See pr5-04.cpp

55 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

56 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

57 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

58 Input Validation using the do-while Loop
do { cout << "Enter a number (1-100) and" << " I will guess it. "; cin >> number; } while (number < 1 || number > 100);//Invalid. // … Code to use the valid number goes here.

59 Input Validation: while Loop Example
cout << "Enter a number (1-100) and" << " I will guess it. "; cin >> number; while (number < 1 || number > 100)//outside range { cout << "Number must be between 1 and 100." << " Re-enter your number. "; } // … Code to use the valid number goes here.

60 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’);

61 (2-dimensional patterns)
STOP / START HERE Chapter 5 Repetition / Loops part 7 – Nested loops (2-dimensional patterns) See pr8-09.cpp

62 5.10 Deciding Which Loop to Use
while: pretest loop (Not sure how many repetitions, possibly zero) Patterns: RCU, CU do-while: post test loop (must execute body at least once, e.g., menu-driven) Patterns: RC for: pretest loop (counter or sequence controlled loop)

63 5.11 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; } outer loop inner loop See pr5-14.cpp

64 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 product of number of repetitions of the two loops. In previous example, inner loop repeats 9 times

65 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

66 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++) Can omit loop body if all work is done in header

67 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; } See pr5-12.cpp

68 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; } See pr5-12.cpp

69 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<ENTER><EOF> 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<EOF> , 33 is read but eof() true. But after the extraction, the buffer contains only whitespace (but <EOF> is not exposed, so eof() is false, and there appears to be data in InBuffer. InBuffer: <ENTER><EOF>

70 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 See pr5-16.cpp

71 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 File pr5-17.cpp corresponds to program 5-17 on pp in the text. See also file pr5-17B.cpp as a solution to the problems discussed in program 5-17.


Download ppt "Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition"

Similar presentations


Ads by Google