So far we have looked at two uses for while loops. In the first, we repeated a
loop until the user entered an acceptable value. In the second, we repeated a
loop until a numerical computation converged. In this final example, we will
use a loop to perform a summation.
Recall the cantilevered brick problem that we studied in an earlier lesson.
The key computation that we performed was the summation
Let's write a C program that will perform this summation for different values
of n. It is possible to translate this summation almost directly into a
while loop. Try to answer the following two questions:
- What needs to happen on each trip through the loop?
- How many trips through the loop will be necessary?
Click here for the answers
Having answered these questions, you should have a pretty good idea of what the
loop will look like. See if you can implement the loop before looking at our
answer.
Click here for the answer
What do we need to do before the loop begins to ensure proper operation?
Click here for the answer
You can see the final version of our summation code in
``examples/summation.c''. Alternatively, you can view it
directly.
Joseph L. Zachary
Hamlet Project
Department of Computer Science
University of Utah