TOPIC 4.5 · STUDY

Implementing Array Algorithms

Students traverse a one-dimensional int array with an index loop to run standard algorithms: minimum, maximum, sum, average, and count. A sum or count starts at 0; a min or max starts at the first element. An int average uses integer division unless a double cast happens first.

4.5.A

Traverse the array

An array algorithm walks every index once and updates a tracker. Stay with a one-dimensional int array and a for loop on i. Do not use ArrayList or a 2D array here.

Five patterns appear again and again. Sum: start total at 0 and add each element. Minimum: start least at arr[0], then compare from index 1; do not start least at 0 unless every value is known nonnegative and the problem says so. Maximum mirrors minimum with a greater-than update. Average: finish the sum, then divide by arr.length; with two ints that is integer division. Count: start a counter at 0 and increment only when an if test succeeds.

int[] vals = {5, 3, 8, 2};
int sum = 0;
for (int i = 0; i < vals.length; i++) {
    sum += vals[i];
}
System.out.print(sum);

sum begins at 0. The loop adds 5, then 3, then 8, then 2, so the running total is 5, 8, 16, and finally 18. The console prints 18. The same loop shape finds a maximum by starting most at vals[0] and replacing it whenever vals[i] is larger, or a minimum by starting least at vals[0] and replacing it whenever vals[i] is smaller.

Four array cells hold 5, 3, 8, and 2. A fifth cell shows the finished running total 18.

Each slot feeds the accumulator. After four adds, total holds 18.

For average, print sum / vals.length after the loop. Both operands are int, so 18 / 4 is 4, not 4.5. To keep a fractional mean, cast before dividing, such as (double) sum / vals.length. A count of values that meet a test uses the same index walk: int kept = 0; then if (vals[i] meets the rule) kept++;.

Key points

  • Traverse with for (int i = 0; i < arr.length; i++) and read arr[i].
  • Sum and count start at 0; min and max start at arr[0].
  • Update minimum with < and maximum with > as you scan later indexes.
  • Average is sum / arr.length; int / int truncates toward zero.
  • Count increments only when the if test succeeds.
  • Use a 1D int array only; no ArrayList and no 2D arrays.

Integer division drops the fraction unless you cast before dividing.

Practice this topic