Introduction to Java Programming Comprehensive Version 10th
Introduction to Java Programming, Comprehensive Version (10th Edition)
Methods And Arrays
You are given two arrays that represent the components of a vector as shown here.
double[] vec1 = {0.5,0.6,0.2};
double[] vec2 = {1.0,0.0,0.2};
a. Write a method named computeDotProduct that will take in two double arrays (a,b) as parameters and returns a double value.
b. The dot product is the sum of the products of each pair of elements in the two vectors. Set dotProduct equal to 0. Use a loop to sum go through each element in the array. (Hint: dotProduct = dotProduct + a[i]*b[i])
c. Make the method flexible enough that it will accept the arrays of various lengths and will check that the array arguments are of the same length. (Hint: Use a property of the array).
d. Call this method from within the main with the two arrays vec1 and vec2 as arguments.
Solution
public class dotproduct
{
public static void main(String[] args)
{
double[] vec1 = {0.5,0.6,0.2};
double[] vec2 = {1.0,0.0,0.2};
double dotProduct = computeDotProduct(vec1,vec2);
System.out.println(\"Dot Product : \" + dotProduct);
}
public static double computeDotProduct(double[] vec1, double[] vec2)
{
int m = vec1.length;
int n = vec2.length;
double dotProduct = 0;
if(m == n)
{
for(int i = 0; i< m; i++)
for(int j = 0; j< n; j++)
dotProduct += vec1[i]*vec2[j];
}
return dotProduct;
}
}
