Title: Computing Fundamentals with C
 1C and Object-Oriented Programming Flow 
Control Repetition (Looping) 
 2Repetition Looping
- Goals 
- Recognize and use the Determinate Loop pattern 
- Recognize and use the indeterminate loop pattern 
- Exercises 
- Programming Projects 
- Use the C do while statement 
- Design Loops 
- Exercises 
- Programming Projects 
- There are two sets of exercises and programming 
 projects
3Repetitive Control
- The following algorithms involve repetition 
- Add the remaining flour ¼ cup at a time whipping 
 until smooth.
- While there are more burger/fries/soda orders, 
 sum each item. Apply tax. Display Total.
- Compute a course grade for every student. 
- While the ATM is running, process another 
 customer, and allow many transactions.
- Microwave the food until the timer reaches 0, the 
 cancel button is hit, or the door is opened.
4Why is repetition needed?
- To take advantage of the computer's speed in 
 order to perform the same tasks faster.
- To avoid writing the same statements over and 
 over again (shorter programs).
- To traverse a collection of objects. 
- To make programs general enough to handle various 
 sized collections of data.
- Consider code intended to average exactly 100 
 numbers (next slide)
5Average 100 values the hard way
- int sum  0 
- cout ltlt "Enter number " // lt-Repeat these three 
 
- cin gtgt number // lt- statements for 
 each
- sum  sum  number // lt- number in the set 
- cout ltlt "Enter number " 
- cin gtgt number 
- sum  sum  number 
- // ...291 statements deleted ... 
- cout ltlt "Enter number " 
- cin gtgt number 
- sum  sum  number 
- average  sum / 100
How many statements are required for 100 
inputs____? What changes are necessary to average 
200 inputs ____?  
 6Algorithmic Pattern The Determinate loop
- There is a better way. 
- We often need to perform some action a specific 
 number of times
- Produce 89 paychecks. 
- Count down to 0 (take 1 second of the clock). 
- Send grade reports to 75,531 Penn State students 
- The determinate loop pattern repeats some action 
 a specific number of times.
7(No Transcript) 
 8 Determinate Loops
- This template repeats a process n times (you fill 
 in the comments)
-  n  / how often we must repeat the process / 
-  for (count  1 count lt n count  count  1) 
 
-   
-  / the process to be repeated / 
-   
- determinate loops must know the number of 
 repetitions before they begin
- know exactly how many employees, or students, or 
 whatever, that must be processed.
9The C for loop--determinate loops 
-  for ( initial statement  loop-test  
 update-step )
-   
-  repeated-part 
-   
- When a for loop is encountered, the 
 initial-statement is executed. The loop-test
 evaulates. If the loop-test is false, the for
 loop is terminated. If loop-test is true, the
 repeated-part is executed and the update-step
 executes.
10Flow chart view of a for loop
Initial statement
True
False
Loop test
Iterative part
update-step 
 11Example for loop that produces an average
- int n 
- double number, ave 
- double sum  0.0 
- // get a value for the number of iterations 
- cout ltlt "How many numbers? " 
- cin gtgt n 
- for(int counter  1 counter lt n counter  
 counter  1)
-  // Iterate the same three statements n times 
-  cout ltlt "Enter number " 
-  cin gtgt number 
-  sum  sum  number 
-  
- // Compute and display the average (pre n gt 0) 
- ave  sum / n 
- cout ltlt "Average " ltlt ave ltlt endl
12Demonstration
- Active Learning, Write the output  
-  int j, n  5 
-  for(j  1 j lt n j  j  1) 
-   
-  cout ltlt j ltlt endl 
-   
-  
-  for(int k  10 k gt 0 k  k - 2) 
-   
-  cout ltlt k ltlt endl 
-   
-  
-  Optional Demo forloops.cpp
13Other Incrementing Operators
- It is common to see determinate loops of this 
 form where n is the number of repetitions
-  for(j  1 j lt n j)  
-  // ... 
- The unary  and -- operators add 1 and subtract 
 1 from their operands, respectively.
-  int n  0 
-  n // n is now 1 Equivalent to nn1 or 
 n1
-  n // n is now 2 
-  n-- // n is now 1 again 
- The expression count is equivalent to the more 
 verbose count  count  1
14Other Assignment Operators
- C has several assignment operators in addition 
 to  (- and )
- j - 2 is the equivalent of j  j - 2 
- sum  x is the equivalent of sum  sum  x 
- What is sum when a user enters 7 and 8? 
-  int sum  0, x  0 
-  cout ltlt "Enter a number " 
-  cin gtgt x // user enters 7 
-  sum  x 
-  cout ltlt "Enter a number " 
-  cin gtgt x // user enters 8 
-  sum  x 
15Determinate loops with grid objects
- This code surrounds the grid with blocks, no 
 matter what its size is
-  for(r  0 r lt g.nRows() r) 
-   
-  g.block(r, 0) // block west 
-  g.block(r, g.nColumns() - 1) // block east 
-   
-  for(c  1 c lt g.nColumns() - 1 c) 
-   
-  g.block(0, c) // block north 
-  g.block(g.nRows() - 1, c) // block south 
-  
16Application of the determinate loop pattern
- Find the range of test scores where range is 
 defined as the highest minus the lowest.
- So if the input of 4 test scores is 70, 80, 90, 
 and 100, then what is the range _____?
- Prelude to the range problem 
- Imagine finding the largest number in a list of 
 thousands of numberswe need a systematic method
 (we cant just glance at the list).
17Analysis 
- Problem Write a program that determines a range 
 (highest-lowest) of tests. The user must enter
 the number of tests to check.
- Inputs The number of test scores to scan, and 
 The actual test scores.
- Output The range 
- Active Learning Name the objects well need 
-  _________ _________ _______ _______ 
18Design
- Start with this algorithm 
- 1. Obtain the number of test scores. 
- 2. Determine the range. 
- 3. Display the range. 
- You might notice that the process step, 
 "Determine the range", needs further refinement
- The first step is a prompt/input pattern and the 
 third step is simply labeled output.
19Design (con.)
- // 1. Obtain the number of test scores 
- cout ltlt "Enter number of test scores " 
- cin gtgt n 
- //////////////////////////// 
- // 2. Determine the range // 
- //////////////////////////// 
- // 3. Display the range 
- cout ltlt "Range  " ltlt range 
- So let's concentrate on the second step. 
- Since range is defined as highest-lowest, we need 
 to find the highest and lowest.
20Design (con.)
- We need the actual test scores for input to 
 determine the highest and lowest.
- As each new test score is input, we compare it to 
 the highest so far, and also to the lowest so
 far.
- But what do we compare the first test to? 
- How about something very large for the smallest 
 and something very small for the largest.
- Then the first number is compared to these fake 
 values.
21Design (con.)
- In a side by side comparison, we see test is 
 greater than the fake largest (-1000) and less
 than the fake smallest (1000)
22Design (con.)
- So, before we start reading tests, lets 
 initialize highest and lowest like this
-  double highest  -1000 
-  double lowest  1000 
- Then we need to do the following n times 
-  Input a test. 
-  Compare test to highest, Trace 
 algorithm
-  and if necessary, store the 
 with inputs of
-  test as the highest so far. 
 87 91 72
-  Compare test to lowest, 
-  and if necessary, store the 
-  test as the lowest so far.
23Use the determinate loop" pattern again
- We do this n times. Do you see the pattern? 
-  // 2. Determine the range Demonstrate 
 range.cpp
-  for(counter  1 counter lt n counter) 
-   
-  // The process to repeat n times 
-  cout ltlt "Enter test " 
-  cin gtgt test 
-  if (test gt highest) 
-  highest  test 
-  // check for lowest ? _______ ? 
-   
-  // assert highest stores the largest test 
-  // and lowest stores the smallest test 
-  range  highest - lowest 
24Why bother?
- It should be noted, that this computer based 
 range problem is more cumbersome than just
 scanning a small list of tests for the highest
 and lowest.
- But imagine thousands of inputs in a file which 
 we cannot see.
- We could use the same pattern, but someone must 
 count the inputs before starting.
- There must be a better way.
25Algorithmic pattern The Indeterminate Loop
- Determinate loops have a limitation 
- We must know n in advance. 
- Many situations when repeat a set of statements 
 an unspecified number of times
- Processing report cards for every student in a 
 school (or paychecks for all employees, or...)
- Allowing 1 to many ATM transactions. 
- Asking the user for specific input and allowing 
 re-entry of input after invalid inputs.
-  NAME ANOTHER ? ________________ ?
26Some Events that terminate indeterminate loops
- An indeterminate loop repeats a process until 
 some stopping event terminates the repetition.
- There are many such events, but we'll focus on 
 these events only
- User enters a special value indicating end of 
 data.
- A logical expression becomes false. 
- The grid mover hits the wall or an edge 
- The end of a file is encountered. 
- indeterminate loops do not need to know n in 
 advance--indeterminate loops to determine n.
27Pattern indeterminate loop Problem Some 
process must repeat an unknown number of times 
so some event is needed to terminate the 
loop. Algorithm while(the termination event has 
not occurred)  perform these actions 
 bring the loop closer to termination  Code 
 while(myGrid.frontIsClear()) Example  
myGrid.putDown() myGrid.move()   
 28The while loop
- The indeterminate loop pattern can be 
 imple-mented with the C while loop there are
 other ways
- while ( loop-test ) 
-  
-  repeated-part 
-  
- When a while statement is encountered the block 
 (statements between  and  )execute while (as
 long as) the loop-test is true.
29Flow chart view of while-loop execution
False
True
loop-test
statement-1
Iterative Part
statement-2
statement-n 
 30Using while to Implement Determinate loops 
- This loop terminates when j lt n becomes false. 
- The event that terminates this loop is j gt n 
-  int j  1 
-  int n  4 
-  while(j lt n) 
-   
-  cout ltlt j ltlt " " 
-  j 
-   
- Output _______ ?
31indeterminate loop pattern with grid objects 
-  grid g(5, 10) 
-  // assert g is a 5x10 grid surrounded by blocks 
-  // with one opening and the mover in a random 
 spot
-  while(g.frontIsClear()) 
-   
-  g.move(1) 
-   
-  g.display() 
-  // Output (exit could be anywhere on an edge) 
-            
-   . . . . . . . .  
-   lt . 
-   . . . . . . . .  
-           
32indeterminate loop with a Sentinel
- A sentinel is a specific input from the user ot 
 signal that there is no more data.
- The sentinel should be the same type of dats 
- The sentinel must not be in the valid range of 
 data
- Example Use -1 as the sentinel for test scores 
 that can only be in the range of 0 through 100
-  Enter test scores or -1 to quit 
-  80 95 76 82 56 100 45 86 -1
33Using cin gtgt as a loop test
- An extraction itself may exist as a loop-test in 
 an if...else or while statement
- if(cin gtgtintObject) or while(cin gtgtintObject) 
- This simplifies the loop 
-  // Priming extraction is part of the loop test 
-  while( (cin gtgt test)  (test ! -1) ) 
-   // now process the test 
-  sum  test 
-  n 
-   
34Using stream extraction as a loop test
- Example evaluation of the loop-test when 95 is 
 input for test
-  while( (cin gtgt test)  (test ! -1) ) 
-  ( true )  ( 95 ! -1) ) 
-  true  true 
-  true 
- Demonstrate cin extraction as the loop-test with 
 sentinel.cpp
35Infinite loops
- Infinite loop a loop that never terminates. 
- Infinite loops are usually not desirable. 
- Here is an example of an infinite loop 
-  cin gtgt test 
-  while(test ! -1) 
-   // now process the test 
-  sum  test 
-  n 
-   
- There is no step that brings the loop closer to 
 termination.
36Loop Selection and Design 
- The following outline is offered to help you 
 choose and design loops in a variety of
 situations
- Determine which type of loop to use 
- Determine the loop-test 
- Write the statements to be repeated 
- Bring the loop one step closer to termination 
- Initialize objects if necessary 
37Determine Which Type of Loop to Use 
- The number of repetitions is known in advance or 
 read as input, use a counter-controlled for loop.
 The loop must stop when some event occurs during,
 use an event-controlled while loop. When the loop
 must always execute once (to validate input), use
 a do-while loop
38Determine the Loop-Test
- Try writing the conditions that must be true for 
 the loop to terminate.
-  inputName  "QUIT" // Termination condition 
- The logical negation (with ! applied) can be used 
 directly as the loop-test of a while loop
-  while( inputName ! "QUIT") // logical negation
39Write the Statements to be Repeated 
- This is why the loop is being written in the 
 first place. This may be done after other parts.
-   
-  cout ltlt "Enter number " 
-  cin gtgt x 
-  sum  sum  x 
-  n 
-   
40Bring the Loop one Step Closer to termination
- To avoid an infinite loop, there should be at 
 least one action in the loop body that brings it
 closer to termination.
- Increment the counter by 1. 
- Extract data from an input stream.
41Initialize Objects if Necessary. 
- Check to see if any objects used in either the 
 body of the loop or the loop-test need to be
 initialized. Consider this loop
-  int j, n 
-  double x, sum 
-  while(j lt n) 
-   
-  cout ltlt "Enter a number " 
-  cin gtgt x 
-  sum  sum  x 
-  j 
-   
- Which objects need to be initialized before this 
 while loop is encountered ? _______________ ?