looping a new array java code example

Example 1: 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<nums.length; i++) {
    if (nums[i] == target) {
      return i; // return the index where the target is found
    }
  }

  // If we get here, the target was not in the array
  return -1;
}

Example 2: arrays with for loops

// Another way to write search that combines
// the "end of array" and "found" logic in one
// while loop. As a matter of style, we prefer
// the above version that uses the standard
// for-all loop.
public int searchNotAsGood(int[] nums, int target) {
  int i = 0;
  while (i<nums.length && nums[i]!=target) {
    i++;
  }
  // get here either because we found it, or hit end of array
  if (i==nums.length) {
    return -1;
  }
  else {
    return i;
  }
}

Tags:

Java Example