| |
For each of the following problems, make sure that you do not make any assumptions about the
size of the array that is going to be passed to the method you write.
- Modify the program ArrayGrades to use an input correction loop
so that it will only accept grades in the range 0 to 100 (inclusive), prompting the
user to re-enter if they supply a grade out of range.
- Write a method which takes an array of
doubles and returns
the sum of the squares of the elements in the array.
Insert the method definition into the following program so that you can test it:
// Program: ArrayTest
import HMC.HMCSupport;
class ArrayTest {
public static void main(String args[]) {
double[] a = {5.2,2,8.8,4,-1.3,10,-12.1};
HMCSupport.out.println("The array being tested:");
printArray(a);
HMCSupport.out.print("The sum of the squares is: ");
HMCSupport.out.println(sumOfSquares(a));
}
// Insert your method here
// ...
public static void printArray(double[] arr) {
HMCSupport.out.println();
for (int i = 0 ; i < arr.length ; i++) {
HMCSupport.out.print(arr[i] + " ");
}
HMCSupport.out.println();
}
}
|
- Write a method which takes an array of
doubles and returns
the largest value in the array.
Add it to the ArrayTest program along with lines in main that will test it.
Make sure you do not make any assumptions about the possible range of values in the array.
In particular, don't assume the numbers are all positive, and don't rely on knowing the
value of the smallest possible java double value.
- Modify the test program so it declares, allocates, and initializes a second
array of
doubles, b, of the same length as the array a.
(Just pick any set of values to put in the second array.)
Add to the last program a method which takes two arrays and computes and returns the
sum of the squares of the placewise difference between the elements of the two arrays.
Add lines to main to test the method on the two arrays.
- Add a method that computes the dot-product of two vectors.
Recall that for two n-dimensional vectors, A and B,
A.B = A1B1 + ... + AnBn
Test this on the two vectors used from the last problem.
- Add a method that computes the length (or, magnitude), |A|, of a vector, A, which is the
square root of the sum of the squares of the individual components. Note that you can
compute the sum of the squares manually (using a loop), or note that it is the result of taking the
dot product of the vector with itself.
- Recall that for two n-dimensional vectors, A and B, the dot-product also satifies
the equation:
A.B = |A||B|cos(theta)
where theta is the angle between the two vectors. Use this fact, the dot product method from the
last problem, and the method Math.acos to write a method which, given two vectors,
computes and returns the angle theta (in radians) between them. Test this method as before.
|