Finding Array Sum and Average

Finding the sum and average of an array involves accumulating all the values stored inside the array into a single total amount. Think of emptying your piggy bank and adding up all the coin values one by one to find your total savings. In Java, we use a loop to traverse every element, adding each va

The ideaLink to this section

Finding the sum and average of an array involves accumulating all the values stored inside the array into a single total amount. Think of emptying your piggy bank and adding up all the coin values one by one to find your total savings. In Java, we use a loop to traverse every element, adding each value to a running accumulator variable. Once the loop finishes, we divide this total sum by the number of elements to get the average. This technique is essential for processing numerical collections like temperatures, salaries, or test scores.

note

When to use it: Use this idea when you need to calculate totals, aggregates, or arithmetic means of numerical data stored in an array.

Worked example: Total and Average Daily ExpensesLink to this section

A college student wants to find out the total money spent over a week and the average daily expenditure. Given an array of expenses for each day, calculate the sum and average.

Input format

  • Line 1: an integer N, the number of days
  • Line 2: N space-separated integers representing the expense for each day

Output format

  • Line 1: the total sum of expenses
  • Line 2: the average daily expense formatted as an integer or decimal

How it worksLink to this section

  1. Read N = 4 and prepare to read 4 expense values.
  2. Read 100, add to sum (sum = 100).
  3. Read 200, add to sum (sum = 300).
  4. Read 150, add to sum (sum = 450).
  5. Read 50, add to sum (sum = 500).
  6. Calculate average as 500 / 4 = 125.0 and print sum and average.

note

Time complexity: O(n). We visit each element of the array once to compute the sum. Space complexity: O(n). We store n elements in the array.

warning

A common beginner mistake when computing averages in Java is integer division, where dividing two integers like 5 / 2 results in 2 instead of 2.5. Always cast one of the numbers to a double.

Quick checkLink to this section

Finding Array Sum and Average quiz
Question 1 of 2

Why is it important to cast the sum or count to a double when calculating an average?

Practice 1: Total Weight of Luggage (Medium)Link to this section

tip

Hint: Create a sum variable starting at 0, then loop through the array to add each bag's weight.

Practice 2: Average Temperature Readings (Hard)Link to this section

tip

Hint: Compute the total sum of all temperatures using a loop, then divide by N using double precision.

Rate this content

Sign in to rate

Discussion

Sign in to join the discussion