Question (Java): Complete the following class methods. The dotProduct method has
ID: 3709185 • Letter: Q
Question
Question (Java): Complete the following class methods. The dotProduct method has been completed for you. Use your knowledge of methods and the descriptive name of the methods to determine what you should implement. What is printed? Indicate below:
public class soMuchMath {
// Create an array of size N and set each value to val static double[] initArray(double val, int N) {
}
// Add the variable val to all elements (Note: do not *set* them to val!)
static void addValToArray(double[] arr, int N, double val) {
}
// Dot (inner) product of two vectors
static double dotProduct(double[] iaA, double[] iaB, int N) {
double ans = 0.0;
for(int ii = 0; ii < N; ii++)
ans += iaA[ii] * iaB[ii];
return ans;
}
public static main(String[] args) {
final int sz = 4;
double[] vec1 = initArray(1.0, sz);
double[] vec2 = initArray(2.0, sz);
addValToArray(vec2, sz, Math.Pi)
double dot = dotProduct(vec1, vec2, sz);
System.out.print("The dot product is " + dot);
}
}
Explanation / Answer
Complete program of the given program. Changes has been added:
public class soMuchMath
{
//Create an array of size N and set each value to val
static double[] initArray(double val, int N)
{
//Creating an array of size N
double[] arr= new double[N];
//for loop to set each value to val;
for(int i=0;i<arr.length;i++)
{
//set each value to val;
arr[i]=val;
}
//returning array
return arr;
}
//Add the variable val to all elements (Note: do not *set* them to val!)
static void addValToArray(double[] arr, int N, double val)
{
//for loop to set each value to val;
for(int i=0;i<N;i++)
{
//set each value to val;
arr[i]=val;
}
}
// Dot (inner) product of two vectors
static double dotProduct(double[] iaA, double[] iaB, int N)
{
double ans = 0.0;
for(int ii = 0; ii < N; ii++)
ans += iaA[ii] * iaB[ii];
return ans;
}
//main method return type should be void
public static void main(String[] args)
{
final int sz = 4;
double[] vec1 = initArray(1.0, sz);
double[] vec2 = initArray(2.0, sz);
addValToArray(vec2, sz, Math.PI);
double dot = dotProduct(vec1, vec2, sz);
System.out.print("The dot product is " + dot);
}
}
Output:
The dot product is 12.566370614359172