Next: Finding the mode. Up: Array examples. Previous: None.
Textbook: Sections 5.3 and 5.4
The most common thing you'll want to do to an array is to walk through the array doing something. I want to look at one particular thing you might want to do to an array: find a particular element within the array.
To do this, we might go through the array looking for possible matches. When we find a match, we stop.
Notice that in this case it was important that we define i outside the for loop, since we wanted to use its final value after the for loop also.int i; for(i = 0; i < arr.length; i++) { if(arr[i] == value) break; } if(i == arr.length) { IO.print(value + " not found in array"); } else { IO.print(value + " found at array index " + i); }
Next: Finding the mode. Up: Array examples. Previous: None.