4️⃣

9.4 Applications of Arrays

Chapter Table of Contents

#️⃣
Ch. 9 Arrays

Section Table of Contents

Average Score

Here is an application of an array in a program, which could be used by a teacher to calculate the average of 5 test scores.

// prompt user for 5 test scores
        Scanner input = new Scanner(System.in);
        System.out.print("Enter 5 test scores, separated by spaces: ");

        // store the scores in an array
        double[] scores = new double[5];
        for (int i = 0; i < scores.length; i++) {
            scores[i] = input.nextDouble();
        }

        input.close();

        // calculate the sum of the scores
        double sum = 0;
        for (double score : scores) {
            sum += score;
        }

        // calculate the average and display it
        double average = sum / 5;
        System.out.println("The average score is " + average);

Sample output:

Enter 5 test scores, separated by spaces: 45 99 89 97 23
The average score is 70.6

Multiple Inputs

Before, we only used Scanner for getting 1 value after a prompt. In this program, you’ll notice that in the highlighted portion of the code, nextDouble() is being called repeatedly. This allows us to read multiple double values, as long as they are separated by space. This kind of way to get user input can also be used for other Scanner methods such as nextInt().

⚖️

Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.