Traversing a 1D array means using a loop to visit its elements in order so you can read, calculate, search, or update values. The main tools are an indexed for loop, a while loop with an index, and an enhanced for loop. For AP Computer Science A, choose an indexed loop when you need positions or updates and an enhanced loop when you only need to read values.
Why This Matters for the AP Computer Science A Exam
Array traversal is one of the most heavily used skills in AP Computer Science A. Unit 4 carries a large share of the exam, and traversal shows up constantly in both multiple-choice and free-response code writing.
On multiple-choice questions you will often trace traversal code to predict output, decide which loop visits the right elements, or explain why a segment will not compile or runs incorrectly. When an array is not given to you, you can make a small sample array and trace the loop on it. In free-response code writing, you frequently traverse arrays to compute results, search for values, or update elements, so a reliable loop pattern saves time and prevents bugs.

Key Takeaways
- Traversing an array uses a repetition statement to access all elements or an ordered sequence of them.
- An indexed
forloop orwhileloop accesses elements by index, so you can read or changearray[i]directly. - An enhanced
forloop gives you a copy of each element through the loop variable, without using an index. - Reassigning the enhanced
forloop variable does not change the array; assigning through an index likearray[i] = valuedoes. - When an array stores object references, you can call methods on the enhanced
forloop variable to change that object's attributes, but the stored references stay the same. - Any enhanced
forloop over an array can be rewritten as an indexedforloop or awhileloop.
The Three Ways to Traverse a 1D Array
Indexed for loop
The indexed for loop is the most flexible traversal. You control the starting index, the stopping condition, and how the index changes each pass. Because you have the index, you can read and modify elements directly with array[i].
</>Javaint[] scores = {85, 92, 78, 96, 88}; for (int i = 0; i < scores.length; i++) { System.out.println(scores[i]); }
The standard pattern starts i at 0, continues while i < array.length, and increases i by 1. Valid indices run from 0 to array.length - 1, so using < instead of <= keeps you in bounds.
You need an index when you want to:
- modify elements with
array[i] = value - compare elements at different positions, like
array[i]andarray[i + 1] - traverse in reverse using
i-- - work with two arrays at the same position
while loop with an index
A while loop traverses by index too. You just manage the index yourself: declare it before the loop, check it in the condition, and update it inside the loop.
</>Javaint[] scores = {85, 92, 78, 96, 88}; int i = 0; while (i < scores.length) { System.out.println(scores[i]); i++; }
Forgetting to update the index inside a while loop creates an infinite loop, which is a common trap. Anything you can write with an indexed for loop you can also write with a while loop.
Enhanced for loop (for-each)
The enhanced for loop visits each element in order without using an index. Each pass copies the current element into the loop variable.
</>Javaint[] scores = {85, 92, 78, 96, 88}; for (int score : scores) { System.out.println(score); }
The loop variable type must match the element type. This loop is clean for reading values, but it has an important limit: the variable is a copy of the element, not the element itself.
Copy Semantics: The Most Tested Idea Here
The enhanced for loop variable holds a copy of each element. Reassigning that variable changes only the copy, not the array.
</>Javaint[] nums = {1, 2, 3}; for (int n : nums) { n = n * 10; // changes the copy, not the array } // nums is still {1, 2, 3}
To actually change stored values, use an index:
</>Javaint[] nums = {1, 2, 3}; for (int i = 0; i < nums.length; i++) { nums[i] = nums[i] * 10; // changes the array } // nums is now {10, 20, 30}
Arrays of objects behave a little differently
When an array stores object references, the enhanced for loop variable copies the reference, which still points to the same object. That means you can call methods on the loop variable to change the object's attributes, and those changes stick because both the variable and the array element point to the same object.
</>Java// Assume Student has a method addPoints(int p) for (Student s : roster) { s.addPoints(5); // modifies the actual Student object }
What you cannot do is replace the stored reference by reassigning the loop variable. Writing s = new Student(...) inside the loop only changes the copy, so the array still holds the original reference.
Rewriting One Loop as Another
These three loops produce the same output. Being able to convert between them helps when a problem requires an index you do not have, or when you want to trace code more carefully.
</>Javaint[] data = {4, 8, 15, 16, 23}; // Enhanced for loop for (int value : data) { System.out.println(value); } // Indexed for loop for (int i = 0; i < data.length; i++) { System.out.println(data[i]); } // while loop int i = 0; while (i < data.length) { System.out.println(data[i]); i++; }
If a task asks you to modify elements or use positions, switch from an enhanced for loop to an indexed for loop or while loop so you have the index available.
Traversal Patterns You Will Reuse
These patterns all build on the same loop structure. What changes is the work inside the loop. The standard algorithms that depend on these traversals (sums, max, counts, and so on) are covered more fully in 4.5 Implementing Array Algorithms, but the traversal itself is the foundation.
</>Javaint[] scores = {85, 92, 78, 96, 88, 73, 91}; // Sum and average int total = 0; for (int i = 0; i < scores.length; i++) { total += scores[i]; } double average = (double) total / scores.length; // Count elements that meet a condition int highScores = 0; for (int i = 0; i < scores.length; i++) { if (scores[i] >= 90) { highScores++; } } // Find the index of the maximum value int maxIndex = 0; for (int i = 1; i < scores.length; i++) { if (scores[i] > scores[maxIndex]) { maxIndex = i; } }
Notice the loop structure stays the same. Only the body changes based on what you need.
How to Use This on the AP Computer Science A Exam
Code Tracing
When you trace traversal code, write down the index and any running variables for each pass. Track the loop bound carefully: a loop with i <= array.length will reach an invalid index and throw an ArrayIndexOutOfBoundsException. If no array is provided, build a small one like {3, 1, 4} and step through it.
Free Response
When you write a method that traverses an array, pick the loop that matches the job. If you only read values, an enhanced for loop is clean. If you change elements or need positions, use an indexed for loop or while loop. Double-check your bounds and your accumulator's starting value before moving on.
Common Trap
Watch for code that reassigns an enhanced for loop variable and expects the array to change. The array stays the same. Also check whether a method needs to visit every element (like an average) or can stop early once it finds a match.
Common Misconceptions
- Assigning a new value to an enhanced
forloop variable does not change the array. To change stored values, use an index and writearray[i] = value. - Calling a method on an enhanced
forloop variable that is an object reference does change that object. People mix this up with reassignment, but modifying an object's attributes is different from replacing the reference. - Valid indices stop at
array.length - 1. Usingi <= array.lengthruns one step too far and throws anArrayIndexOutOfBoundsException. - The array's
lengthis an attribute written asarray.lengthwith no parentheses. It is not a method call likearray.length(). - An enhanced
forloop does not give you the index. If you need the position of an element, use an indexedforloop or awhileloop instead. - A
whileloop used for traversal needs you to update the index yourself. Leaving out thei++creates an infinite loop.
Related AP Computer Science A Guides
Vocabulary
The following words are mentioned explicitly in the College Board Course and Exam Description for this topic.Term | Definition |
|---|---|
array index | The numeric position used to access a specific element in an array. |
array traversal | The process of using repetition statements to systematically access elements in an array. |
enhanced for loop | A Java loop construct that iterates through all elements of a collection without using an index variable. |
enhanced for loop variable | The variable in an enhanced for loop header that is assigned a copy of each array element during each iteration. |
indexed for loop | A loop that accesses array elements by using their index positions to control iteration. |
object reference | A value that points to the memory location where an object is stored, allowing access to that object. |
traverse | To visit each element in a data structure (such as a string, array, or ArrayList) in a systematic way, often using recursion. |
while loop | An iterative statement that repeatedly executes a block of code as long as a specified Boolean expression evaluates to true. |
Frequently Asked Questions
What does traversing an array mean in AP CSA?
Traversing an array means using a loop to access every element or an ordered sequence of elements. In AP CSA, you commonly traverse arrays to print values, search for a value, calculate totals, or update elements.
When should you use an indexed for loop to traverse an array?
Use an indexed for loop when you need the index, need to change array elements, compare neighboring elements, traverse backward, or use the same index across multiple arrays. The standard pattern is i = 0 while i < array.length.
When should you use an enhanced for loop with an array?
Use an enhanced for loop when you only need to read each element in order and do not need the index. It is shorter and cleaner, but the loop variable receives a copy of each element.
Can an enhanced for loop change array values?
Reassigning the enhanced for loop variable does not change the value stored in the array. To replace array elements, use an indexed loop and assign directly with array[i] = newValue.
How do enhanced for loops work with arrays of objects?
For arrays of object references, the enhanced for loop variable receives a copy of the reference. Calling methods on that object can change its attributes, but assigning the loop variable to a new object does not replace the reference stored in the array.
What is a common AP CSA mistake when traversing arrays?
A common mistake is using i <= array.length instead of i < array.length. Valid array indices run from 0 to array.length - 1, so using <= can cause an ArrayIndexOutOfBoundsException.