User Tools

Site Tools


cs257:hw3sol

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Next revision
Previous revision
cs257:hw3sol [2015/09/18 11:08]
scarl created
cs257:hw3sol [2015/09/18 11:15] (current)
scarl
Line 1: Line 1:
 1. Method to copy the first ''​count''​ elements from one array to another 1. Method to copy the first ''​count''​ elements from one array to another
 +
 <code java> <code java>
-   /** copyFront - copy a subset of elements from source to destination array +/** copyFront - copy a subset of elements from source to destination array 
-     ​* @precondition count > 0 && src.length >= count && dest.length >= count +  * @precondition count > 0 && src.length >= count && dest.length >= count 
-     ​* @postcondition src[0]..src[count-1] are the same as dest[0]..dest[count-1] +  * @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) { +public static void copyFront(int[] src, int[] dest, int count) { 
-      if (count <= 0 || src.length < count || dest.length < count) { +   ​if (count <= 0 || src.length < count || dest.length < count) { 
-         ​throw IllegalArgumentException("​Invalid value for count: " + count); +      throw IllegalArgumentException("​Invalid value for count: " + count);
-      } +
-      for (int i = 0; i < count; i++) { +
-         ​dest[i] = src[i]; +
-      }+
    }    }
 +   for (int i = 0; i < count; i++) {
 +          dest[i] = src[i];
 +   }
 +}
 </​code> ​   </​code> ​  
 +
 2. Method to zero out "every other" element of an array 2. Method to zero out "every other" element of an array
 +
 <code java> <code java>
-   /** zeroEven - set all even numbered indices of array arr to zero +/** zeroEven - set all even numbered indices of array arr to zero 
-     ​* @precondition arr != null +  * @precondition arr != null 
-     ​* @postcondition arr[0] = arr[2] = arr[4] ... = 0 +  * @postcondition arr[0] = arr[2] = arr[4] ... = 0 
-     ​* / +  * / 
-   ​public static void zeroOut(int[] arr) { +public static void zeroOut(int[] arr) { 
-      if (arr == null) { +   ​if (arr == null) { 
-        throw NullPointerException("​Array has not yet been created"​);​ +     ​throw NullPointerException("​Array has not yet been created"​);​ 
-      +   ​
-      for (int i = 0; i < arr.length; i+=2) { // counts up by twos +   ​for (int i = 0; i < arr.length; i+=2) { // counts up by twos 
-         ​arr[i] = 0; +      arr[i] = 0;
-      }+
    }    }
 +}
 </​code>​ </​code>​
 +
 +3. Use __enhanced for loop__ to count the number of elements in an array
 +
 +
 +  // 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.1442592529.txt.gz · Last modified: 2015/09/18 11:08 by scarl