Traversing Arrays with For Loops
Index Variables: 6.2.1
- You can use a variable or expression inside the brackets for an array index
double[] testScores = {90.0, 45.5, 83.0};
int index = 1;
testScores[index] = 70.0;
double combinedScores = testScores[index] + testScores[index - 1];
For Loop to Traverse Arrays: 6.2.2
- You can iterate an array using a for loop
- called
traversing
an array - start at 0, loop while the index is less than the length of the array
- variable
i
is often used in loops- short for index
- called
double[] testScores = {90.0, 45.5, 83.0};
for (int i = 0; i < testScores.length; i++) {
System.out.println("Test score is " + testScores[i]);
}
Arrays Are Objects!
Remember that Arrays in Java are objects! If you pass one in as a parameter, know that you are passing an object reference, and any change to that array will effect the array outside the method too.
Looping back to front: 6.2.3
- You can loop however you want! Just do the math :)
double[] wheelSpeeds = {1.0, 3.0, 4.7, 2.4};
for (int i = wheelSpeeds.length-1; i >= 0; i--) {
System.out.println(wheelSpeeds[i]);
}
Common Errors when looping through arrays: 6.2.5
- The first index is 0!
- The last index is
arrayName.length - 1
- An off by one error would result in an
ArrayIndexOutOfBoundsException
!
Summary: 6.2.7
- Iteration can be used to access all elements in an array
- traversing an array
- elements are accessed using an index
- Arrays start at index 0 and go to length-1!
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
This was adapted from the CS Awesome curriculum, which was created by
Barbara Ericson, Beryl Hoffman, and many other CS Awesome contributors. All rights reserved.
CS Awesome is licensed under CC BY-NC-SA 4.0.