Skip to content

← Back to Overview

Java Program - Array Totals and Averages

Concept Explanation

What is it?

This program iterates through an array of numbers to calculate two key statistics: the total sum of all values and their average (mean).

Why is it important?

Aggregating data is a primary function of arrays. Whether processing student marks, daily sales figures, or temperature readings, calculating totals and averages is a standard requirement.


Algorithm

  1. Start
  2. Declare an array of integers (e.g., numbers).
  3. Initialize sum = 0.
  4. Loop through each element of the array.
  5. Add the current element to sum.
  6. Calculate average = sum / array_length.
  7. Display sum and average.
  8. End

Implementations

import java.util.Scanner;

public class ArrayStats {
    public static void main(String[] args) {
        // Sample Data
        int[] numbers = {10, 20, 30, 40, 50};

        int sum = 0;
        double average;

        // Calculate Sum
        for (int i = 0; i < numbers.length; i++) {
            sum += numbers[i];
        }

        // Calculate Average
        // Cast to double to preserve decimal precision
        average = (double) sum / numbers.length;

        System.out.println("Array Elements: ");
        for (int num : numbers) {
            System.out.print(num + " ");
        }
        System.out.println("\n-------------------");
        System.out.println("Total Sum: " + sum);
        System.out.println("Average:   " + average);
    }
}

Explanation

  • Java
  • Array Length: numbers.length gives the total count of elements.
  • Type Casting: (double) sum is crucial. Without it, integer division would occur (e.g., 150 / 5 = 30), potentially losing decimal values if the average wasn't a whole number.
  • Enhanced For Loop: Used for printing elements cleanly.

Complexity Analysis

  • Time Complexity: O(n) - We visit every element once.
  • Space Complexity: O(1) - We only use a few variables for tracking.

Practice Problems

Easy

  • Modify the program to accept 5 numbers from the user.

Medium

  • Find the maximum and minimum values in the same loop.

"Statistics are the grammar of science." - Karl Pearson