loop type for array 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

// For-All variant
// Go through the elements backwards
// by adjusting the for-loop
public void forAllBackwards(int[] nums) {
  for (int i = nums.length-1; i>=0; i--) {
    System.out.println( nums[i] );
  }
}

Tags:

Java Example