methods for looping the array code example

Example 1: 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 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