how to loop 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

int findSmallest(int[] values) {
  int minIndex = 0;  // start with 0th element as min
  for (int i=1; i<values.length; i++) {
    if (values[i] < values[minIndex]) {
      minIndex = i;
    }
  }
  return minIndex;
}

Example 3: arrays with for loops

// Find-Max variant
// Use very small number, Integer.MIN_VALUE,
// as the initial max value.
public int findMax2(int[] nums) {
  int maxSoFar = Integer.MIN_VALUE;  // about -2 billion

  // Look at every element
  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"];