how to create arrays in for loop 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 maxValue) {
      maxIndex = i;
      maxValue = nums[maxIndex];
    }
  }
  return maxIndex;
}

Example 2: 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 maxSoFar) {
      maxSoFar = nums[i];
    }
  }
  return maxSoFar;
}

Tags:

Misc Example