Dale - Computer Science Illuminated 276

Dale - Computer Science Illuminated 276 - posCount to 0. We...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
8.3 Functionality of Imperative Languages 249 A count-controlled loop is very straightforward: The process is repeated a specified number of times. The event-controlled loop is less clear-cut. It may not be immediately apparent what the event should be. Let’s look at a couple of examples. First, let’s read and sum input data values until we read a negative value. What is the event? An input value is positive. How do we initialize the event? We read the first data value. We test the value to determine if it is positive and enter the loop if it is. How do we update the event? We read the next data value. Here is the algorithm. Now let’s write the algorithm for reading and summing positive values until ten have been counted. Ignore zero or negative values. What is the event? The number of positive values read and summed. The means that we must keep a count of the number of positive values as we read them; let’s call it posCount . How do we initialize the event? We set
Background image of page 1
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: posCount to 0. We test posCount against ten, and exit the loop when posCount reaches 11. How do we update the event? We increment posCount each time we read a positive value. Many languages have two additional looping structures. We said that the while structure is a pretest loop. Another type of looping structure is one where the testing occurs at the end of the loop. These loops are called posttest loops, for obvious reasons. Posttest loops always execute the loop Set sum to 0 Initialize sum to zero Set posCount to 0 Initialize event While (posCount <= 10) Test event Read a value If (value > 0) Test to see if event should be updated Set posCount to posCount + 1 Update event Set sum to sum + value Add value into sum ... Statement(s) following loop Read a value Initialize event While (value >= o) Test event ... Body of loop Read a value Update event ... Statement(s) following loop...
View Full Document

Ask a homework question - tutors are online