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
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
- Read N = 4 and prepare to read 4 expense values.
- Read 100, add to sum (sum = 100).
- Read 200, add to sum (sum = 300).
- Read 150, add to sum (sum = 450).
- Read 50, add to sum (sum = 500).
- Calculate average as 500 / 4 = 125.0 and print sum and average.
note
warning
Quick checkLink to this section
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
Practice 2: Average Temperature Readings (Hard)Link to this section
tip
Rate this content
Sign in to rate
Discussion
Sign in to join the discussion