for 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 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

Example 3: arrays with for loops

// Search
// Searches through the given array looking
// for the given target. Returns the index number
// of the target if found, or -1 otherwise.
// (classic search-loop example)
public int search(int[] nums, int target) {
  // Look at every element
  for (int i=0; i

Tags:

Misc Example