how to do a for loop for arrays code example
Example 1: arrays with for loops
// Find-Max variant -- rather than finding the max value, find the
// *index* of the max value
public int findMaxIndex(int[] nums) {
int maxIndex = 0; // say the 0th element is the biggest
int maxValue = nums[0];
// Look at every element, starting at 1
for (int i=1; i<nums.length; i++) {
if (nums[i] > maxValue) {
maxIndex = i;
maxValue = nums[maxIndex];
}
}
return maxIndex;
}
Example 2: arrays with for loops
// Another way to write search that combines
// the "end of array" and "found" logic in one
// while loop. As a matter of style, we prefer
// the above version that uses the standard
// for-all loop.
public int searchNotAsGood(int[] nums, int target) {
int i = 0;
while (i<nums.length && nums[i]!=target) {
i++;
}
// get here either because we found it, or hit end of array
if (i==nums.length) {
return -1;
}
else {
return i;
}
}