/** Simple program to illustrate the use of arrays. Here we ask the user * to enter 10 values, and we find the average, standard deviation, * max and min values. * * Note that it is possible to write this program more efficiently, * and we will explore better techniques later in the course. * This program is just an example showing how to use loops and arrays. */ import java.util.Scanner; public class Array { public static void main(String [] args) { Scanner kbd = new Scanner(System.in); // declare an array "a" of 10 real numbers double [] a = new double[10]; // initialize by asking for input int i = 0; while (i < 10) { System.out.print("enter score #" + (i+1) + " --> "); a[i] = kbd.nextDouble(); i = i + 1; } //////////////////////////////////////////////////////////////////// // First we need to find the average before the standard deviation. double sum = 0.0; i = 0; while (i < 10) { sum += a[i]; i = i + 1; } double average = sum / 10; //////////////////////////////////////////////////////////////////// // The formula to find the standard deviation is as follows: // For each score, find its deviation (difference) from the average, // square it, add these squared values, divide by the number of // values, then take the square root. sum = 0.0; i = 0; while (i < 10) { double diff = a[i] - average; sum += diff * diff; i = i + 1; } double standardDeviation = Math.sqrt(sum / 10); //////////////////////////////////////////////////////////////////// // Now find the extremes of the array. // To save time, I'll use the same loop to find both the max & min, // rather than write one loop for each. // We assume that the first number in the array is the max (or min), // and then continue the search starting with the 2nd element. double max = a[0]; double min = a[0]; i = 1; while (i < 10) { if (a[i] > max) max = a[i]; if (a[i] < min) min = a[i]; i = i + 1; } //////////////////////////////////////////////////////////////////// // output System.out.printf("\nAverage = %.2f\n", average); System.out.printf("Standard deviation = %.2f\n", standardDeviation); System.out.printf("Max value = %.2f\n", max); System.out.printf("Min value = %.2f\n", min); } }