how to loop arrays code example
Example 1: arrays with for loops
public int findMaxIndex(int[] nums) {
int maxIndex = 0;
int maxValue = nums[0];
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
int findSmallest(int[] values) {
int minIndex = 0;
for (int i=1; i<values.length; i++) {
if (values[i] < values[minIndex]) {
minIndex = i;
}
}
return minIndex;
}
Example 3: arrays with for loops
public int findMax2(int[] nums) {
int maxSoFar = Integer.MIN_VALUE;
for (int i=0; i<nums.length; i++) {
if (nums[i] > maxSoFar) {
maxSoFar = nums[i];
}
}
return maxSoFar;
}
Example 4: how to use for loops to work with array in javascript
let myArray = ["one", "two", "three", "four"];