1D Arrays
IB Syllabus: B2.2.2 - Describe the characteristics of a 1D array. Construct algorithms using 1D arrays.
Table of Contents
- Key Concepts
- Worked Examples
- Quick Code Check
- Trace Exercise
- Code Completion
- Spot the Bug
- Output Prediction
- Practice Exercises
- GitHub Classroom
- 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
lengthis a field (no parentheses), not a method. Writingscores.length()is a compile error. Compare withString: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
iruns from0toscores.length - 1. Accessingscores[scores.length]causes anArrayIndexOutOfBoundsException.
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
ArrayListworks 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);
| i | numbers[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.
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
-
Input and Print - Write code in
mainthat 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). -
Find Minimum - Given
int[] temps = {22, 18, 25, 15, 20}, find and print the minimum value and the index where it occurs. -
Count Above Threshold - Given
int[] scores = {72, 85, 60, 91, 45, 78}, count and print how many scores are 70 or above. -
Sum of Even Elements - Given an array of integers, calculate and print the sum of only the even values.
Extension
-
Reverse Copy - Create a reversed copy of
{1, 2, 3, 4, 5}without modifying the original. Print both arrays to verify. -
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
- Resize and Insert - Given
int[] data = {10, 20, 30, 40, 50}, write code that creates a new array one element larger, inserts the value25at index 2, and shifts the remaining elements right. The result should be{10, 20, 25, 30, 40, 50}.
GitHub Classroom
Codespace Setup Instructions (click to expand)
First Time Setup
- Click “Open in GitHub” above, then click the green “Accept this assignment” button
- 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
- Wait for your repository to be created, then click “Open in Codespace”
- Wait for the Codespace to finish loading (you’ll see VS Code in your browser)
Important: Switch to Standard Mode
- Look at the bottom status bar. If it says
Java: Lightweight Mode, click on it and select Standard - Wait for Java to finish loading (status bar will say
Java: Ready) - 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
- Open
src/ArraysCore.java. This is the only file you need to edit - Complete each
// TODOsectionOpen src/ArraysCore.java first, implement the TODOs, then run ./run-tests.sh in the Codespaces Terminal. - Click the Run button (▶ above
main) to test your output - 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
maininArraysCore.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.shand 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
- Click the Source Control icon (branch icon) in the left sidebar
- Type a message like
completed tasksin the message box - Click the green Commit button
- If asked “stage all changes?” → click Always
- Click Sync Changes → if asked about push/pull → click OK, Don’t Show Again
- Done! Autograding runs automatically. Your teacher can see your results in the GitHub Classroom dashboard
How to Review Feedback
- Go to your repository on GitHub
- Click the “Pull requests” tab at the top
- Open the pull request called “Feedback”
- Click the “Files changed” tab. You’ll see your teacher’s comments on specific lines of your code
- Read through each comment carefully, then fix your code in Codespaces
- Run
bash run-tests.shin your Codespaces Terminal to check your fixes - Commit and push again (repeat steps 12-17). The autograder will re-run automatically
Connections
- Prerequisites: Selection & Iteration (loops needed for traversal)
- Related: Searching Algorithms (linear & binary search operate on arrays)
- Next: 2D Arrays (arrays of arrays)
- Forward: ArrayList (coming soon as sub-page), Sorting (rearranging array elements)