Use loops to process arrays

Arrays 📦

Imagine a row of lockers in your school hallway. Each locker has a number (the index) and can hold one item (the value). In programming, an array is just a similar row of lockers that stores data.

Key facts:

  • All items in an array are the same type (e.g., all integers, all strings).
  • Array indices start at 0 and go up to length‑1.
  • Arrays are fixed size once created (in Java).

Exam Tip

Remember: array.length gives the number of elements, not the highest index. Use for (int i = 0; i < array.length; i++) to avoid off‑by‑one errors.

Looping Through an Array 🔁

Loops let you visit each locker one by one. The most common loops are:

  1. For loop – good when you know how many times to run.
  2. While loop – good when you stop based on a condition.
  3. Do‑while loop – runs at least once.

Example: Find the sum of all numbers in an array.

int[] scores = {85, 92, 78, 64, 100};
int sum = 0;
for (int i = 0; i < scores.length; i++) {
    sum += scores[i];
}
System.out.println("Total = " + sum);
  

The math behind it: $${\displaystyle \sum_{i=0}^{n-1} a_i}$$ where $n$ is the array length.

Exam Tip

When writing a loop, always check the loop condition: i < array.length is safer than i <= array.length because the latter will try to access an index that doesn’t exist.

Common Array Operations 🧩

Operation Example Code
Find maximum value
int max = array[0];
for (int i = 1; i < array.length; i++) {
    if (array[i] > max) max = array[i];
}
  
Count occurrences of a value
int target = 5;
int count = 0;
for (int val : array) {
    if (val == target) count++;
}
  
Reverse the array
int n = array.length;
for (int i = 0; i < n/2; i++) {
    int temp = array[i];
    array[i] = array[n-1-i];
    array[n-1-i] = temp;
}
  

Exam Tip

When you’re asked to write a loop, start by writing the loop header, then the body, and finally the update statement. Double‑check that the loop variable starts at the correct index and ends before array.length.

Practice Problem 🚀

Given the array int[] data = {3, 7, 2, 9, 4, 6};, write a loop to:

  1. Calculate the average (use double for precision).
  2. Print each element that is greater than the average.

Try it on your own, then compare with the solution below.

int[] data = {3, 7, 2, 9, 4, 6};
int sum = 0;
for (int val : data) {
    sum += val;
}
double avg = (double)sum / data.length;
System.out.println("Average = " + avg);
for (int val : data) {
    if (val > avg) System.out.println(val + " is above average");
}
  

Exam Tip

When calculating averages, cast the sum to double before dividing to avoid integer truncation.

Revision

Log in to practice.

1 views 0 suggestions