Skip to lesson

Sum, average, largest and search

Most array programs do one of a few jobs: add up all the elements, find the largest or smallest, count matches, or search for a value. Each job is one loop plus one extra variable.

Total and average

Your report card needs the total and the average of 5 marks. Keep a running total that starts at 0 and add each element; the average is then the total divided by marks.length.

Example 1 · Total and average of 5 marks

Average.javaJava
public class Average {    public static void main(String[] args) {        int[] marks = {78, 85, 62, 90, 71};        int total = 0;        for (int m : marks) {            total += m;        }        double average = (double) total / marks.length;        System.out.println("Total: " + total);        System.out.println("Average: " + average);    }}
Output
Total: 386
Average: 77.2

What this code does

  • total starts at 0 before the loop and collects every mark: 78 + 85 + 62 + 90 + 71 = 386.
  • (double) total turns the total into a decimal before dividing, so 386 / 5 keeps its decimal part: 77.2.

Without the cast, two int values divide as whole numbers: 386 / 5 gives 77, not 77.2 (Type conversion and casting (opens in a new tab)).

Largest and smallest

A week of temperatures: which day was the hottest? Keep the best value so far in max, start it at the first element, and replace it whenever an element is bigger.

Example 2 · Hottest and coolest day

MaxMin.javaJava
public class MaxMin {    public static void main(String[] args) {        int[] temps = {31, 35, 29, 36, 33, 30, 34};        int max = temps[0];        int min = temps[0];        for (int t : temps) {            if (t > max) {                max = t;            }            if (t < min) {                min = t;            }        }        System.out.println("Highest: " + max);        System.out.println("Lowest: " + min);    }}
Output
Highest: 36
Lowest: 29

What this code does

  • Both max and min start at the first temperature, 31.
  • Each round, a bigger value replaces max and a smaller one replaces min: the smallest is the same job with <.

Never start max at 0. Winter mornings in Leh are all below 0, so no element is bigger than 0 and the answer would wrongly be 0. Step through it with those numbers:

Trace the code

Warmest morning in Leh

public class WarmestMorning {
public static void main(String[] args) {
int[] temps = {-4, -9, -2, -7};
int max = temps[0];
for (int t : temps) {
if (t > max) {
max = t;
}
}
System.out.println("Warmest: " + max);
}
}

Variables

temps
{-4, -9, -2, -7}

Output

(nothing printed yet)

Line 3Four morning temperatures, all below 0.

Step 1 of 12

Counting matches

The coach wants to know how many overs went for 10 or more runs, not which ones. Keep a counter that starts at 0 and add 1 only when an element passes the check, as in Understanding loop flow (opens in a new tab).

Example 3 · Count the big overs

CountOvers.javaJava
public class CountOvers {    public static void main(String[] args) {        int[] runs = {6, 12, 4, 15, 9, 10};        int count = 0;        for (int r : runs) {            if (r >= 10) {                count++;            }        }        System.out.println("Overs with 10 or more runs: " + count);    }}
Output
Overs with 10 or more runs: 3

What this code does

  • count goes up by 1 only for 12, 15 and 10.
  • Change the condition and the same loop counts passed students, hot days or days present.

Searching for a value

Is roll number 107 on the list, and where? Check the elements one by one, a linear search: start position at -1 ("not found"), store i when you find the value, then stop with break (opens in a new tab).

Linear search for 107

Step 1 of 4

Array: 101, 104, 107, 110, 113. i at index 0.
target
107
position
-1
Look for 107. position starts at -1, which means "not found yet". i = 0: 101 is not 107, so move on.

Example 4 · Search for a roll number

FindRoll.javaJava
public class FindRoll {    public static void main(String[] args) {        int[] rolls = {101, 104, 107, 110, 113};        int target = 107;        int position = -1;        for (int i = 0; i < rolls.length; i++) {            if (rolls[i] == target) {                position = i;                break;            }        }        System.out.println("Index of " + target + ": " + position);    }}
Output
Index of 107: 2

What this code does

  • This is an index loop, because the answer is a position, i.
  • At index 2 the check rolls[i] == target is true: the loop saves 2 in position and break ends it.

If target were 112, nothing would match and position would stay -1. No real index is -1, so check position == -1 before you use the answer as an index.

Next step

Check your understanding

10 quick questions