Answers for "for loops for arrays"

0

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;
  }
}
Posted by: Guest on May-15-2020
0

arrays with for loops

// For-All
// Do something for every element
public void forAll(int[] nums) {
  for (int i=0; i<nums.length; i++) {
    System.out.println( nums[i] );
  }
}
Posted by: Guest on May-15-2020

Browse Popular Code Answers by Language