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
15 exercises across 6 Java files: traversal, counting, transformation, copying, resizing, plus the GradeArray mini-project. Autograded with 58 JUnit tests.
Codespace Setup Instructions (click to expand)

First Time Setup

  1. Click “Open in GitHub” above, then click the green “Accept this assignment” button
  2. Check the email registered with your GitHub account – click the link there to open your repository. This avoids access issues and means your teacher does not need to share links manually
  3. Wait for your repository to be created, then click “Open in Codespace”
  4. Wait for the Codespace to finish loading (you’ll see VS Code in your browser)

Important: Switch to Standard Mode

  1. Look at the bottom status bar. If it says Java: Lightweight Mode, click on it and select Standard
  2. Wait for Java to finish loading (status bar will say Java: Ready)
  3. Without Standard Mode, the Run button won’t work and you’ll get “Main method not found” errors

Dismiss Popups

You’ll see two notification popups. Dismiss them both:

  • “Would you like VS Code to periodically run git fetch?” → Click No
  • “There’s a pull request associated with main” → Click Don’t Show Again

These are housekeeping popups, not part of the assignment.

How to Code

  1. Open src/ArraysCore.java. This is the only file you need to edit
  2. Complete each // TODO sectionOpen src/ArraysCore.java first, implement the TODOs, then run ./run-tests.sh in the Codespaces Terminal.
  3. Click the Run button (▶ above main) to test your output
  4. Compare your output with the expected output written in the comments above each task

How to Check Your Code

You can check your work in two ways:

Option A: Run your code directly

  • Click the Run button (▶) above main in ArraysCore.java
  • Compare your printed output with the expected output shown in the comments above each task

Option B: Run the autograder tests

  • Open the Terminal (Menu → Terminal → New Terminal)
  • Type bash run-tests.sh and press Enter
  • Green ✓ = test passed, Red ✗ = test failed
  • Each test tells you what it expected. Read the error message to fix your code

How to Submit

  1. Click the Source Control icon (branch icon) in the left sidebar
  2. Type a message like completed tasks in the message box
  3. Click the green Commit button
  4. If asked “stage all changes?” → click Always
  5. Click Sync Changes → if asked about push/pull → click OK, Don’t Show Again
  6. Done! Autograding runs automatically. Your teacher can see your results in the GitHub Classroom dashboard

How to Review Feedback

  1. Go to your repository on GitHub
  2. Click the “Pull requests” tab at the top
  3. Open the pull request called “Feedback”
  4. Click the “Files changed” tab. You’ll see your teacher’s comments on specific lines of your code
  5. Read through each comment carefully, then fix your code in Codespaces
  6. Run bash run-tests.sh in your Codespaces Terminal to check your fixes
  7. Commit and push again (repeat steps 12-17). The autograder will re-run automatically

Connections


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

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