Introduction
Welcome to the FiveHive website article for topic 4.4!
Today, our learning targets, according to AP® Computer Science A Course and Exam Description 2025, are as follows:
4.4.A Develop code used to traverse the elements in a 1D array and determine the result of these traversals.
Logically, after learning how to store your data in arrays, that begs the question: how can we search through that data to check it/use it? In this lesson, that is what we plan to cover!So sit back, and pay attention! Let’s jump right in. Get excited!
What is Array Traversal?
Traversing an array means visiting each element in sequence to perform operations like printing values, calculating sums, finding extremes, or modifying elements.
Without traversal, accessing every element requires individual statements:
int[] scores = {85, 92, 78, 88, 95};
System.out.println(scores[0]);
System.out.println(scores[1]);
System.out.println(scores[2]);
System.out.println(scores[3]);
System.out.println(scores[4]);Notice how tedious that is? If we want to display multiple elements in an array, especially when the array is a gajillion elements in length, this ain’t it chief. We have to be more efficient.
The way we automate this process is by using loops! That is the heart of what traversing an array is: using repetition statements to access multiple array elements in a sequence!
Indexed For Loop Traversal
We can use for or while loops to traverse arrays! For now let’s focus on former.
Regardless of what you use, you’ll likely use an index variable that increments as the traversal goes on to access elements via indices, like so:
for (int i = 0; i < array.length; i++) {
// Access array[i]
}Notice:
-
i = 0: Start at first index -
i < array.length: Continue while index is valid -
i++: Move to next index -
Access elements using
array[i]
Here is a more concrete example:
int[] numbers = {10, 20, 30, 40, 50};
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}When to Use Indexed For Loops
Use indexed for loops when you need:
- The index value: To know position while processing
- To modify elements: Changing values in the array
- Backward traversal: Going from end to beginning
- Non-sequential access: Skipping elements or accessing neighbors
While Loop Traversal
Arrays can also be traversed using while loops, though for loops are more common. Here is the while loop notation (notice that here, you need to define the index variable and explicitly increment it yourself):
int i = 0;
while (i < array.length) {
// Access array[i]
i++;
}Here is a more concrete example:
int[] numbers = {5, 3, -2, 8, -1, 4};
int i = 0;
boolean found = false;
while (i < numbers.length && !found) {
if (numbers[i] < 0) {
System.out.println("First negative: " + numbers[i]);
found = true;
}
i++;
}Who is who?
You may ask: when do I use either of these methods? You’ll usually use for loops. But for while loops, use when you aren’t sure when you’ll reach the end.
Enhanced For Loop
An enhanced for loop (also called "for-each" loop) provides a simpler syntax for traversing arrays when you don't need indices. Syntax can be found below:
for (dataType element : array) {
// The variable “element” (call the enhanced for loop variable) will store the value the loop has reached in its traversal.
}
Here is an example:
int[] numbers = {10, 20, 30, 40};
for (int num : numbers) {
System.out.println(num);
}This reads as: "For each num in numbers, print num."
Important Limitation: Cannot Modify Array
Assigning a new value to the enhanced for loop variable does not change the value stored in the array.
int[] values = {1, 2, 3, 4, 5};
for (int val : values) {
val = val * 2; // Does NOT change the array!
}
// Array is still: {1, 2, 3, 4, 5}The loop variable val is a copy of the array element, not a reference to it. Changing the copy doesn't affect the original. If you want to modify elements use an indexed for loop array.
Enhanced For Loop with Objects
When an array stores object references, the attributes can be modified by calling methods on the enhanced for loop variable. This does not change the object references stored in the array.
// Assume Student class exists with getName() and setGrade() methods
Student[] students = new Student[3];
// ... students array populated ...
// This works → modifying object attributes
for (Student s : students) {
s.setGrade(s.getGrade() + 5); // Curves each student's grade
}This works because the loop variable s is a copy of the reference, but both the copy and the original reference point to the same object. Calling methods modifies that object.
The following will NOT work:
for (Student s : students) {
s = new Student("New"); // Does NOT change array!
}Reassigning s changes the copy, not the reference stored in the array.
Converting Between Loop Types
It is easy to convert between all three loop traversal types we covered today! The conversions are shown below:
Enhanced For Loop Version:
String[] names = {"Alice", "Bob", "Charlie"};
for (String name : names) {
System.out.println(name);
}Equivalent Indexed For Loop:
for (int i = 0; i < names.length; i++) {
System.out.println(names[i]);
}Equivalent While Loop:
int i = 0;
while (i < names.length) {
System.out.println(names[i]);
i++;
}All three produce identical outputs.
Alright folks I think that’s all she wrote. Let’s now practice!
