Arithmetic Mean

Line: Array Line
Medium DifficultyArrays Learning Outcome One Learning Outcome Three Learning Outcome Four Walkthrough
Type: Walkthrough
You should have completed:

Multiple Choice Question

This topic leads to:

Monthly Calendar

Summary

Arrays are very useful for handling multiple values of the same data type having the same purpose, such as prices, names, and so on. In this exercise you will calculate the mean of a series of numbers by using an array. For N numbers, x, the mean is calculated as (x1 + x2 + ... + xN) / N, or the sum of all the numbers divided by how many there are.

Task

  1. Create a console application
  2. In the Main method:
    1. declare an array of floats
    2. initialise that array to the values 3.4, 6.7, 8.3, 9.0 and 2.4
    3. declare a float variable for the result, initialise it to 0
    4. create a for loop to iterate over that array
    5. in the loop, use the loop counter variable (e.g. index) to get the "current" element of the array, and add that value to the result
    6. after the loop, divide the result by the length of the array (i.e. by the number of numbers we just added together).
    7. Display the number to the user, and check that it is 5.96

Questions

  1. How would you modify this program to allow the user to enter five numbers of their choosing?
  2. How would you further change the program so the user could also decide how many numbers they wanted to enter?