For Loops

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:

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