Java · Beginner level

Beginner level · Module 3: Arrays, Strings and ArrayList · Lesson 1 of 3

Arrays and Array Algorithms

Store a fixed number of values in an array and use loops to total, average, search and find the largest value.

In this lesson you will

  • Declare, fill and read arrays using indexes
  • Write loops for total, average, maximum and linear search

Key concepts

index from 0lengthenhanced forArrayIndexOutOfBoundsException

The lesson

An array holds a fixed number of values of one type: int[] sales = {12000, 8500, 15000};. Indexes start at 0, so sales[0] is 12000 and the last element is sales[sales.length - 1]. Reading sales[3] here throws ArrayIndexOutOfBoundsException.

The enhanced for loop, for (int s : sales), visits every element and is the clearest way to total or print values. Use a normal for loop with an index when you need the position, for example to report which day had the highest sales.

To find a maximum, start with the first element as the best so far and compare each remaining element with it. To search, compare each element with the target and stop when you find it. These two patterns appear in almost every program that handles data.

Step by step

  1. Create an array of seven daily sales values.
  2. Total and average them with an enhanced for loop.
  3. Find the maximum and the index where it occurs.
  4. Search for a value and print its position or 'not found'.
Code example

Weekly sales report with arrays

Total, average and best day from a week of shop sales, using two parallel arrays and one loop.

JavaWeeklySales.java
public class WeeklySales {    public static void main(String[] args) {        String[] days = {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"};        int[] sales = {12000, 8500, 15000, 9800, 17500, 21000, 6400};         int total = 0;        int best = 0; // index of the best day so far        for (int i = 0; i < sales.length; i++) {            total += sales[i];            if (sales[i] > sales[best]) {                best = i;            }        }        double average = (double) total / sales.length;         System.out.printf("Total:   %,d SSP%n", total);        System.out.printf("Average: %,.2f SSP%n", average);        System.out.printf("Best day: %s (%,d SSP)%n", days[best], sales[best]);    }}

Output

Total:   90,200 SSP
Average: 12,885.71 SSP
Best day: Sat (21,000 SSP)

How it works

The two arrays are parallel: days[i] names the day whose sales are in sales[i]. One index-based loop adds each value to the total and remembers the index of the highest value so far, which is why the day's name can be printed at the end. The cast (double) total prevents integer division, so the average keeps its decimals. %,d and %,.2f add thousands separators (shown here for an English locale). Figures are illustrative training data.

Key concepts

parallel arraysindex-based for looprunning maximumcasting to avoid integer division

Practice activity

Write a weekly sales report that prints each day's sales, the total, the average and the best day by name.

Expected result: The report names the day with the highest sales and its amount, and the totals match a calculator check.

Check your understanding

  1. What is the index of the last element of an array a?

    Show answer

    a.length - 1

  2. When should you use an index-based for loop instead of the enhanced for loop?

    Show answer

    When you need the element's position, for example to report or change it.

Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.