Why do we use for loops with arrays? code example
Example 1: arrays with for loops
// Find-Max
// Given a non-empty array of ints, returns
// the largest int value found in the array.
// (does not work with empty arrays)
public int findMax(int[] nums) {
int maxSoFar = nums[0]; // use nums[0] as the max to start
// Look at every element, starting at 1
for (int i=1; i<nums.length; i++) {
if (nums[i] > maxSoFar) {
maxSoFar = nums[i];
}
}
return maxSoFar;
}
Example 2: arrays with for loops
// Search
// Searches through the given array looking
// for the given target. Returns the index number
// of the target if found, or -1 otherwise.
// (classic search-loop example)
public int search(int[] nums, int target) {
// Look at every element
for (int i=0; i<nums.length; i++) {
if (nums[i] == target) {
return i; // return the index where the target is found
}
}
// If we get here, the target was not in the array
return -1;
}