The while loop that appears in the implementation of trapezoid is
a counting loop. This means that it runs a predetermined number of times
(in our case, N-1 times) as a variable (in our case, i) counts
upward or downward (in our case, upward) to some fixed limit.
There are four components to every counting loop:
- The counting variable is initialized before the loop begins. (In
our case, we are initializing i to 1.)
- The value of the counting variable is used to control whether or not the
loop should continue. (In our case, we are testing whether or not i has
become as large as N.)
- The counting variable is incremented or decremented at the end of each
iteration of the loop. (In our case, we add 1 to i.)
- Something else happens in the body of the loop. (In our case, we add
something to sum.)
C provides another looping statement, called the for loop, that is
convenient for coding counting loops. A for loop looks like this:
for (<initialize counter> ; <test counter> ; <increment counter>) {
<loop body>
}
Here, the things in angle brackets stand for the four components of a counting
loop. The advantage of using a for loop for counting loops is that the
four components are easier to identify.
For example, here is a for loop that adds up all of the integers from 1
to N:
sum = 0;
for (i = 1; i <= N; i = i+1) {
sum = sum + i;
}
See if you can figure out how to reimplement trapezoid using a for
loop.
Click here for the answer
Christopher R. Johnson
Hamlet Project
Department of Computer Science
University of Utah