Matheion

MA-JAVA0 · Module 4

Java arrays and loop patterns

Topics: Arrays · length · for-each · Sum and average

Overview

Session 4 — Java arrays and loop patterns

You will allocate fixed-length arrays with new or literals, read .length, iterate with indexed for and enhanced for, fill arrays from a formula, and compute sums and averages — the same patterns used in tutorial drills like rainfall totals.

Time: about 75 minutes.

Concepts

1. Arrays are objects with fixed length

Declare and allocate:

int[] readings = new int[4];
readings[0] = 21;
readings[3] = 19;

The length lives in readings.length (no parentheses—contrast with String.length()). Valid indices span 0 through length - 1; stepping outside throws ArrayIndexOutOfBoundsException at runtime.


2. Literal initialisers

When you know values up front:

double[] coeffs = {1.0, -0.5, 0.25};

The compiler counts elements and sets the length implicitly.


3. Iteration styles

Indexed loop gives you the index (helpful when indices matter):

for (int i = 0; i < readings.length; i++) {
    System.out.println(i + ": " + readings[i]);
}

Enhanced for (“for-each”) walks values when indices are irrelevant:

for (int v : readings) {
    System.out.println(v);
}

You cannot resize the array inside either loop—the length is fixed at allocation.


4. Copying vs aliasing

Assignment copies the reference, not elements:

int[] a = {1, 2, 3};
int[] b = a; // b points to same array object
b[0] = 99;   // also visible through a[0]

To clone contents use Arrays.copyOf or manual loops:

int[] c = Arrays.copyOf(a, a.length);

Import java.util.Arrays for helper methods like copyOf, fill, sort.


5. Multi-dimensional arrays (preview)

double[][] grid = new double[3][4];

This is an array whose elements are themselves arrays—ragged rows are legal (new double[3][]). Visualise before indexing.


6. Tutorial patterns: sum, average, fill

Accumulate with for-each, then divide by .length:

double sum = 0;
for (double v : readings) {
    sum += v;
}
double average = sum / readings.length;

Fill by relating index to value:

int[] numbers = new int[10];
for (int i = 0; i < numbers.length; i++) {
    numbers[i] = 9 - i; // 9,8,...,0
}

You do not need a second loop just to count elements — that is what .length is for (unless the worksheet asks you to practise counting).


7. Math helpers and random values

Two utility tools show up constantly in intro arrays: Math methods and the Random class.

Math is a class of static helpers that take numbers and return numbers — no object needed:

double big = Math.max(3.0, 7.5);      // 7.5
double low = Math.min(8.0, 2.0);      // 2.0
double d = Math.abs(-4.2);            // 4.2
double root = Math.sqrt(16.0);        // 4.0
double power = Math.pow(2.0, 10.0);   // 1024.0
double roundUp = Math.ceil(2.1);      // 3.0
double roundDown = Math.floor(2.9);   // 2.0
double rounded = Math.round(2.5);     // 3 (long)

Math.random() returns a double in [0.0, 1.0) — zero included, one excluded. Multiply and cast to get a die roll or an array index:

// integer in [0, 5] — six-sided die, minus one
int roll = (int) (Math.random() * 6);        // 0..5
// random index into an array
int[] data = {4, 8, 15};
int pick = data[(int) (Math.random() * data.length)];

Random (from java.util.Random) gives the same idea with more control — a reusable object, a named seed for reproducible runs, and typed draws:

import java.util.Random;

Random rng = new Random();
int dice = rng.nextInt(6) + 1;   // 1..6
boolean flip = rng.nextBoolean(); // true or false
double p = rng.nextDouble();      // [0.0, 1.0)

new Random(42) with a fixed seed produces the same sequence every run — wonderful for debugging and for homework autograders that need stable output.


8. Common pitfalls

  • Length-one-off loops using <= length.
  • Empty arrays — new int[0] is valid; loops simply skip.
  • Printing arrays — System.out.println(arr) prints hash gibberish; use Arrays.toString(arr).

Examples

Example A — two ways to create an array

public class ArrayInit {
    public static void main(String[] args) {
        // 1) size first, then assign
        int[] a = new int[3];
        a[0] = 10;
        a[1] = 20;
        a[2] = 30;

        // 2) literal — length is implied
        double[] arr1 = {10, 20, 30, 40, 50, 60};
        double[] arr2 = {45, -12, 37, 98};

        System.out.println(a.length);    // 3
        System.out.println(arr1.length); // 6
    }
}

Example B — for-each sum and average

public class SumAverage {
    public static void main(String[] args) {
        double[] arr1 = {10, 20, 30, 40, 50, 60};
        double[] arr2 = {45, -12, 37, 98};

        double sum1 = 0;
        for (double v : arr1) {
            sum1 += v;
        }
        double sum2 = 0;
        for (double v : arr2) {
            sum2 += v;
        }
        System.out.println(sum1); // 210.0
        System.out.println(sum2); // 168.0

        double avg1 = sum1 / arr1.length; // 35.0
        double avg2 = sum2 / arr2.length; // 42.0
        System.out.println(avg1);
        System.out.println(avg2);
    }
}

Use for-each when you only need values. Length is the field .length (no parentheses).


Example C — fill an array with a countdown formula

import java.util.Arrays;

public class FillCountdown {
    public static void main(String[] args) {
        int[] numbers = new int[10];

        // 9 down to 0
        for (int i = 0; i < numbers.length; i++) {
            numbers[i] = 9 - i;
        }
        System.out.println(Arrays.toString(numbers));
        // [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

        // 10 down to 1
        for (int i = 0; i < numbers.length; i++) {
            numbers[i] = 10 - i;
        }
        System.out.println(Arrays.toString(numbers));
        // [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
    }
}

Index i counts up; the stored value is a formula of i.


Example G — arithmetic progression in an array

Fill int[20] starting at -10, adding 3 each step: arr[i] = -10 + 3 * i.

public class ProgressionFill {
    public static void main(String[] args) {
        int[] nums = new int[20];
        for (int i = 0; i < nums.length; i++) {
            nums[i] = -10 + 3 * i;
        }
        System.out.println(java.util.Arrays.toString(nums));
        // [-10, -7, -4, -1, 2, 5, 8, 11, 14, 17, 20, 23, 26, 29, 32, 35, 38, 41, 44, 47]
    }
}

First values: -10, -7, -4, -1, 2, … — check i = 0..4 by hand before running.


Example D — rainfall-style total and average

public class RainfallStyle {
    public static void main(String[] args) {
        // Lab starters usually provide rainfall[]; this stand-in has 30 values
        // that total 282 mm (average 9.4), matching a common worksheet check.
        double[] rainfall = {
            12, 8, 0, 15, 9, 11, 7, 14, 10, 6,
            13, 5, 16, 4, 18, 3, 9, 8, 12, 10,
            7, 11, 14, 6, 9, 8, 10, 5, 12, 10
        };

        double totalRainfall = 0;
        for (double mm : rainfall) {
            totalRainfall += mm;
        }

        // Prefer .length — a second counting loop is unnecessary
        int numberMeasurements = rainfall.length;
        double averageRainfall = totalRainfall / numberMeasurements;

        System.out.println("Total rainfall: " + totalRainfall + " mm");   // 282.0
        System.out.println("Average rainfall: " + averageRainfall + " mm"); // 9.4
    }
}

Same skill as Example B: accumulate in a loop, divide by .length.


Example E — safe copy before mutation

import java.util.Arrays;

public class CloneDemo {
    public static void main(String[] args) {
        int[] original = {10, 20, 30};
        int[] working = Arrays.copyOf(original, original.length);
        working[1] = 99;
        System.out.println(Arrays.toString(original)); // 10,20,30
        System.out.println(Arrays.toString(working)); // 10,99,30
    }
}

Example F — optional LCG into an array

A linear congruential generator: $X_{n+1} = (aX_n + c) \bmod m$ (Java %).

public class LcgDemo {
    public static void main(String[] args) {
        int seed = 34;
        int a = 12;
        int m = 100;
        int c = 27;

        int[] randoms = new int[20];
        int x = seed;
        for (int i = 0; i < randoms.length; i++) {
            randoms[i] = x;          // store current, then advance
            x = (a * x + c) % m;
        }
        // first values: 34, 35, 47, 91, 19, ...
    }
}

Combines a while/for update rule with array population — a stretch exercise after sums and averages.


Example H — random fill and a max

Math.random() and Random both populate arrays; the max pattern is the same accumulation habit as sums.

import java.util.Arrays;
import java.util.Random;

public class RandomFill {
    public static void main(String[] args) {
        Random rng = new Random(7);   // fixed seed → reproducible output

        int[] rolls = new int[10];
        for (int i = 0; i < rolls.length; i++) {
            rolls[i] = rng.nextInt(6) + 1;   // die rolls 1..6
        }
        System.out.println(Arrays.toString(rolls));

        double[] prices = new double[8];
        for (int i = 0; i < prices.length; i++) {
            prices[i] = Math.round(Math.random() * 1000) / 100.0; // 0.00..9.99
        }
        System.out.println(Arrays.toString(prices));

        // max over an array — same shape as a sum, but compare-and-keep
        int best = rolls[0];
        for (int v : rolls) {
            if (v > best) {
                best = v;
            }
        }
        System.out.println("largest roll: " + best);
    }
}

With new Random(7), the die rolls are deterministic, so every run of this program prints the same array — that is the point of a seed.

Bridge

Arrays ↔ collections

  1. Fixed length is fast and simple; ArrayList (Session 10) trades flexibility for slightly more syntax.

  2. Algorithms courses reuse the same indexing patterns—master length and copies here.

  3. Varargs methods (String... parts) compile to arrays behind the scenes—recognise the pattern in library APIs.

  4. Data science pipelines often start as arrays of doubles before becoming matrices—same primitive DNA.

When Arrays.toString becomes your friend, you are ready for dynamic lists.

Practice check — arrays and loop patterns

Multiple-choice check from the Matheion app lesson. Pick an answer for each question, then submit.

  1. 1.After `int[] z = new int[3];` and no further assignments, what are `z[0]`, `z[1]`, `z[2]`?

  2. 2.How do you get the number of elements in `double[] arr`?

  3. 3.Which loop correctly adds **every** element of `double[] arr1` into `sum1`?

  4. 4.After `int[] a = {1, 2}; int[] b = a; int[] c = b.clone(); c[0] = 5;`, what is `a[0]`?

  5. 5.To fill `int[] numbers = new int[10];` with values 9 down to 0, which body is correct?

  6. 6.What range of integers does `(int) (Math.random() * 6)` produce?

  7. 7.`Random rng = new Random(42);` — why might you fix the seed?