User Tools

Site Tools


cs257:hw3sol

This is an old revision of the document!


1. Method to copy the first count elements from one array to another

   /** copyFront - copy a subset of elements from source to destination array
     * @precondition count > 0 && src.length >= count && dest.length >= count
     * @postcondition src[0]..src[count-1] are the same as dest[0]..dest[count-1]
     * /
   public static void copyFront(int[] src, int[] dest, int count) {
      if (count <= 0 || src.length < count || dest.length < count) {
         throw IllegalArgumentException("Invalid value for count: " + count);
      }
      for (int i = 0; i < count; i++) {
         dest[i] = src[i];
      }
   }

2. Method to zero out “every other” element of an array

   /** zeroEven - set all even numbered indices of array arr to zero
     * @precondition arr != null
     * @postcondition arr[0] = arr[2] = arr[4] ... = 0
     * /
   public static void zeroOut(int[] arr) {
      if (arr == null) {
        throw NullPointerException("Array has not yet been created");
      }
      for (int i = 0; i < arr.length; i+=2) { // counts up by twos
         arr[i] = 0;
      }
   }

3. Use “enhanced for loop” to count the number of elements in an array <code java>

// After this code fragment is executed, count will be the number of elements in array arr
int count = 0;
for (int item : arr) {
   count++;
}
cs257/hw3sol.1442592635.txt.gz · Last modified: 2015/09/18 11:10 by scarl