Array: Analyze scores

Question: Write a program that reads an unspecified number of scores and determines how many scores are above or equal to the average, and how many scores are below the average. Enter a negative number to signify the end of the input. Assume the maximum number of scores is 100.

Example:


Enter scores:
89
Enter scores:
90
Enter scores:
96
Enter scores:
56
Enter scores:
23
Enter scores:
78
Enter scores:
63
Enter scores:
20
Enter scores:
98
Enter scores:
99
Enter scores:
100
Enter scores:
100
Enter scores:
100
Enter scores:
-4
Average: 77
Scores greater or equal to average: 89 90 96 78 98 99 100 100 100
Scores less than average: 56 23 63 20

package Array;


import java.util.Scanner;

/**
 * Write a program that reads an unspecified number of
 * scores and determines how many scores are above or equal to the average,
 * and how many scores are below the average. Enter a negative number to
 * signify the end of the input. Assume the maximum number of scores is 100.
 * Created by aarushi on 9/5/21.
 */

/*
    Step 1: Create an array of size 100
    Step 2: Input the scores (When negative number is entered terminate the loop)
    Step 3: Calculate the average score
    Step 4: Display cores that are above average
*/
public class ch7ex4 {

    static final int MAX= 100;
    static int length=0;

    public static void main (String [] args){
        int [] scores=  new int[MAX];
        displayArray(scores, inputCalAverage(scores));
    }

    public static int inputCalAverage (int [] scores){
        //create scanner object
        Scanner sc= new Scanner(System.in);
        //create variables to store 
        int average=0, score;

      	//Input scores + calculate average
        for (int i=0; i<MAX; i++){
            System.out.println("Enter scores: ");
            score= sc.nextInt();
            if (score<0) {
                break;
            } else {
                scores[i]=score;
                average+=score;
                length++;
            }
        }
        average/=length;
        System.out.println("Average: " + average);

        return average;
    }

  
  	//display
    public static void displayArray(int [] scores, int average){
        System.out.print("Scores greater or equal to average: ");
        for (int i=0; i<length; i++){
            if (scores[i]>=average){
                System.out.print(scores[i]+ " ");
            }
        }

        System.out.print("\nScores less than average: ");
        for (int i=0; i<length; i++){
            if (scores[i]<average){
                System.out.print(scores[i]+ " ");
            }
        }
    }
}

Leave a Reply

PHP JS HTML CSS BASH PYTHON CODE

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: