Chapter 22.
22.1.
/**
* The number of negative values in the specified array.
*/
public int negativeCount (int[] a) {
int count = 0;
for (int i = 0; i < a.length; i = i+1)
if (a[i] < 0)
count = count + 1;
return count;
}
a[i] == old.a[a.length-1-i]
22.2.
/**
* Reverse the array.
* postcondition: for 0 <= i < a.length
* array maintains that same values but in reverse order
*/
public void reverse (int[] a) {
for (int i = 0; i < a.length/2; i = i+1) {
int temp = a[i];
a[i] = a[a.length-1-i];
a[a.length-1-i] = temp;
}
}
22.3.
/**
* Rotate elements in the array:
* a[0] -> a[1] -> a[2] -> ... -> a[n-1] -> a[0]
* where n = a.length.
*/
public void rotate (int[] a) {
int temp = a[a.length-1];
for (int i = a.length-1; i > 0; i = i-1)
a[i] = a[i-1];
a[0] = temp;
}
22.4.
/**
* The inner product of the specified arrays.
* precondition: v1.length == v2.length
*/
public int innerProduct (int[] v1, int[] v2) {
int sum = 0;
for (int i = 0; i < v1.length; i = i+1)
sum = sum + v1[i]*v2[i];
return sum;
}