Arithmetic Mean
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
- Create a console application
- In the Main method:
- declare an array of floats
- initialise that array to the values 3.4, 6.7, 8.3, 9.0 and 2.4
- declare a float variable for the result, initialise it to 0
- create a for loop to iterate over that array
- 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
- after the loop, divide the result by the length of the array (i.e. by the number of numbers we just added together).
- Display the number to the user, and check that it is 5.96
Questions
- How would you modify this program to allow the user to enter five numbers of their choosing?
- How would you further change the program so the user could also decide how many numbers they wanted to enter?