Exercises
Please complete each exercise or answer the question before reviewing the posted solution comments.
-
Write an algorithm for computing the average of a list of numbers.
- Initialize a variable named
count
to 0. - Initialize a variable named
sum
to 0. - For each value in the list
- Add the value to
sum
. - Add one to
count
.
- Add the value to
- If
count
is greater than zero,
calculate the average by dividingsum
bycount
.
else display no average available for zero values.
If your algorithm is not similar to the one shown above, compare and contrast the differences. These questions can help you with this.
Which algorithm, yours or ours ...
- would be easier to implement?
- is easier to understand?
- would be easier to debug if some part did not work as intended?
- would execute faster?
We don't really expect you to know the answers to these questions. But, we do want you to consider how they might affect the particular algorithm that you choose to implement for a particular problem.
- Initialize a variable named