Exercises

Please complete each exercise or answer the question before reviewing the posted solution comments.

  1. Write an algorithm for computing the average of a list of numbers.

    1. Initialize a variable named count to 0.
    2. Initialize a variable named sum to 0.
    3. For each value in the list
      1. Add the value to sum.
      2. Add one to count.
    4. If count is greater than zero,
      calculate the average by dividing sum by count.
      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.