Traversing Arrays
6.2 Arrays
- Traversing is accessing every value in the array
- Can be done using a loop like a
for
loop orwhile
loop - Below is an example - using a for loop, we can iterate through each fruit in the array of Strings and print it out
// Here is the array we will be working with
String[] myFruits = new String[] {"Apple", "Strawberry", "Watermelon", "Blueberry"};
for (int i = 0; i < myFruits.length; i++) {
System.out.println("Fruit number " + i + " is " + myFruits[i]);
}
- Can also loop through an array in reverse
for (int i = myFruits.length - 1; i >= 0 ; i--) {
System.out.println("Fruit number " + i + " is " + myFruits[i]);
}
- If we have a list of numbers, we could change each value in the array by a certain amount
// Here is the array we will be working with
int[] myNumbers = new int[] {1, 3, 5, 7, 9};
for (int i = 0; i < myNumbers.length; i++) {
// add 10 to each element in the array
myNumbers[i] += 10;
System.out.println("New element " + i + " is " + myNumbers[i]);
}
- We can also traverse an array using a while loop
// Here is the array we will be working with
String[] myFruits = new String[] {"Apple", "Strawberry", "Watermelon", "Blueberry"};
int i = 0;
while (i < myFruits.length) {
System.out.println("Fruit number " + i + " is " + myFruits[i]);
i++;
}
Bound Errors
-
ArrayIndexOutOfBoundsException
thrown, can happen when using loops to access array elements - In the example below instead of the condition being while the index is less than the length of the array, the condition is less than or equal too
- This mean the loop will try to run when i = 4 (since the length of the list is 4). However since array index starts from 0, the last item in the array will have an index of 3. So, index of 4 will be out of bounds, resulting in the error.
int i = 0;
while (i <= myFruits.length) {
System.out.println("Fruit number " + i + " is " + myFruits[i]);
i++;
}
- Given the following code segment, which of the following will cause an infinite loop? Assume that temp is an int variable initialized to be greater than zero and that a is an array of integers.
for ( int k = 0; k < a.length; k++ )
{
while ( a[ k ] < temp )
{
a[ k ] *= 2;
}
}
- A. The values don't matter this will always cause an infinite loop.
- B. Whenever a includes a value that is less than or equal to zero.
- C. Whenever a has values larger then temp.
- D. When all values in a are larger than temp.
- E. Whenever a includes a value equal to temp.