1D Arrays

IB Syllabus: B2.2.2 — Describe the characteristics of a 1D array. Construct algorithms using 1D arrays.

Table of Contents

  1. Key Concepts
    1. Declaration
    2. Access and Modification
    3. Array Length
    4. Traversal
    5. Visual Layout
  2. Worked Examples
    1. Example 1: Find Maximum
    2. Example 2: Sum and Average
    3. Example 3: Count Occurrences
    4. Example 4: Copying Arrays (The Reference Trap)
    5. Example 5: Resizing an Array
    6. Example 6: Duplicate Detection
  3. Quick Code Check
  4. Trace Exercise
  5. Code Completion
  6. Spot the Bug
  7. Output Prediction
  8. Practice Exercises
    1. Core
    2. Extension
    3. Challenge
  9. GitHub Classroom
  10. Connections

Key Concepts

An array stores a fixed number of values of the same type in contiguous memory. Each element is accessed by its index, starting at 0.

Declaration

// Declare with a fixed size — all elements default to 0
int[] scores = new int[5];

// Declare and initialise with known values
int[] scores = {85, 72, 91, 60, 78};

Access and Modification

System.out.println(scores[0]);   // 85 — first element
System.out.println(scores[4]);   // 78 — last element
scores[2] = 95;                  // modify an element

Array Length

System.out.println(scores.length);   // 5 — note: no parentheses, it's a property

length is a field (no parentheses), not a method. Writing scores.length() is a compile error. Compare with String: str.length() uses parentheses because it is a method call.

Traversal

The standard pattern to visit every element:

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

Index i runs from 0 to scores.length - 1. Accessing scores[scores.length] causes an ArrayIndexOutOfBoundsException.

Visual Layout

Index:    0     1     2     3     4
        ┌─────┬─────┬─────┬─────┬─────┐
scores: │  85 │  72 │  95 │  60 │  78 │
        └─────┴─────┴─────┴─────┴─────┘

scores.length = 5
Last valid index = scores.length - 1 = 4

Worked Examples

Example 1: Find Maximum

Start by assuming the first element is the largest, then compare against every other element.

int[] numbers = {34, 67, 12, 89, 45};

int max = numbers[0];   // assume first element is the largest
for (int i = 1; i < numbers.length; i++) {
    if (numbers[i] > max) {
        max = numbers[i];
    }
}
System.out.println("Maximum: " + max);   // Maximum: 89

The loop starts at index 1 because index 0 is already our initial guess. The same pattern works for minimum — just flip > to <.


Example 2: Sum and Average

int[] numbers = {34, 67, 12, 89, 45};

int sum = 0;
for (int i = 0; i < numbers.length; i++) {
    sum = sum + numbers[i];
}
double average = (double) sum / numbers.length;
System.out.println("Sum: " + sum + ", Average: " + average);
// Sum: 247, Average: 49.4

The (double) cast is essential — without it, integer division would truncate the result. 247 / 5 gives 49 in integer arithmetic, but 247.0 / 5 gives 49.4.


Example 3: Count Occurrences

int[] numbers = {34, 67, 12, 67, 45};

int target = 67;
int count = 0;
for (int i = 0; i < numbers.length; i++) {
    if (numbers[i] == target) {
        count++;
    }
}
System.out.println(target + " appears " + count + " time(s).");
// 67 appears 2 time(s).

Example 4: Copying Arrays (The Reference Trap)

Arrays in Java are objects. Assigning one array to another copies the reference, not the data.

// WRONG — both variables point to the same array
int[] original = {1, 2, 3, 4, 5};
int[] copy = original;
copy[0] = 99;
System.out.println(original[0]);   // 99 — original changed too!

The correct way — element-by-element copy:

int[] original = {1, 2, 3, 4, 5};
int[] copy = new int[original.length];

for (int i = 0; i < original.length; i++) {
    copy[i] = original[i];
}

copy[0] = 99;
System.out.println(original[0]);   // 1 — original is untouched

This reference vs copy distinction is one of the most commonly tested concepts in IB exams. Always create a new array and copy elements individually.


Example 5: Resizing an Array

Arrays have a fixed size. To “grow” an array, create a larger one and copy the data across:

int[] data = {10, 20, 30};

// Step 1: Create a larger array
int[] temp = new int[data.length + 2];

// Step 2: Copy elements
for (int i = 0; i < data.length; i++) {
    temp[i] = data[i];
}

// Step 3: Reassign the reference
data = temp;

System.out.println(data.length);   // 5

This resize pattern is exactly how ArrayList works internally — it just does it automatically behind the scenes. Understanding it manually is the point.


Example 6: Duplicate Detection

Compare every pair using nested loops:

int[] numbers = {34, 67, 12, 67, 45};
boolean duplicateFound = false;

for (int i = 0; i < numbers.length - 1 && !duplicateFound; i++) {
    for (int j = i + 1; j < numbers.length && !duplicateFound; j++) {
        if (numbers[i] == numbers[j]) {
            duplicateFound = true;
            System.out.println("Duplicate found: " + numbers[i]
                               + " at index " + i + " and index " + j);
        }
    }
}
// Duplicate found: 67 at index 1 and index 3

The && !duplicateFound condition provides an early exit — no point continuing once a match is found.


Quick Code Check

Q1. Given int[] arr = new int[6], what is the last valid index?

Q2. After int[] b = a; b[0] = 99; — what is a[0]?

Q3. What is arr[0] after int[] arr = new int[4];?

Q4. Which is the correct way to get the size of an array arr?

Q5. What happens when this code runs?

int[] numbers = {10, 20, 30, 40, 50};
for (int i = 0; i <= numbers.length; i++) {
    System.out.println(numbers[i]);
}

Q6. Why does the find-maximum algorithm initialise max = numbers[0] instead of max = 0?


Trace Exercise

Trace this code that finds the maximum value in an array. Fill in the value of numbers[i] and max after each comparison.

int[] numbers = {34, 67, 12, 89, 45};

int max = numbers[0];   // max = 34
for (int i = 1; i < numbers.length; i++) {
    if (numbers[i] > max) {
        max = numbers[i];
    }
}
System.out.println("Maximum: " + max);
inumbers[i]numbers[i] > max?max after
(initial)
1
2
3
4

Final output: Maximum:


Code Completion

Complete the code that creates a reversed copy of an array without modifying the original.

This algorithm maps each element from the original array to its mirror position in a new array. Fill in the blanks to complete the reversed copy:

int[] original = {1, 2, 3, 4, 5};
int[] reversed = new int[];

for (int i = 0; i < original.length; i++) {
    reversed[] = original[i];
}

System.out.println(reversed[0]);  // prints 

Spot the Bug

This code attempts to create an independent copy of an array so the original stays unchanged, but it falls into Java's reference-vs-value trap — modifying the "copy" also changes the original. Click the buggy line, then pick the fix.

1int[] original = {10, 20, 30, 40, 50}; 2 3// Make a copy so we can modify it safely 4// without affecting the original 5int[] copy = original; 6 7copy[0] = 99; 8System.out.println(original[0]); // expects 10

Pick the correct fix for line 5:

Option (a) creates a new array but doesn’t copy the data — all elements would be 0. Option (b) uses .clone() which works but is not covered in IB. The correct IB approach is a loop copy (option c).


Output Prediction

This code demonstrates the accumulator pattern — it traverses an array and builds a running total by adding each element to a sum variable. What is the exact output?

int[] arr = {10, 20, 30, 40, 50};
int sum = 0;
for (int i = 0; i < arr.length; i++) {
    sum = sum + arr[i];
}
System.out.println("Sum: " + sum);

Type your answer:


Practice Exercises

Core

  1. Input and Print — Write code in main that creates an array of 5 integers with the values {8, 3, 15, 7, 12}. Print each element on its own line with its index (e.g., [0] = 8).

  2. Find Minimum — Given int[] temps = {22, 18, 25, 15, 20}, find and print the minimum value and the index where it occurs.

  3. Count Above Threshold — Given int[] scores = {72, 85, 60, 91, 45, 78}, count and print how many scores are 70 or above.

  4. Sum of Even Elements — Given an array of integers, calculate and print the sum of only the even values.

Extension

  1. Reverse Copy — Create a reversed copy of {1, 2, 3, 4, 5} without modifying the original. Print both arrays to verify.

  2. Remove Duplicates — Given {3, 7, 3, 2, 7, 5, 2}, create a new array containing only the unique values (in order of first appearance). Print the result.

Challenge

  1. Resize and Insert — Given int[] data = {10, 20, 30, 40, 50}, write code that creates a new array one element larger, inserts the value 25 at index 2, and shifts the remaining elements right. The result should be {10, 20, 25, 30, 40, 50}.

GitHub Classroom

1D Arrays
Practice array declaration, traversal, and common operations: find max/min, sum, count, copy, and reverse.

Reminder: The GitHub Classroom link above is a placeholder. Update with the actual assignment URL once created.


Connections


Back to top

© EduCS.me — A resource hub for IB Computer Science

This site uses Just the Docs, a documentation theme for Jekyll.