Sophia Ali Sophia Ali - 10 days ago 4
Java Question

Dot product with arrays

In class we had to write a small code using Dot Product to find the sum of two arrays(array a and array b). I have written my code however when I run it it does not give me the answer. My professor said my loop was wrong however I do not think it is. Is the part that says

i<a.length
not allowed in a for loop parameter? Because even if I set it to n it still does not give me the sum.

Here is my code:

public class arrayExample {
public static void main (String [] args) {

int[] a = {1,2,2,1};
int[] b = {1,2,2,1};
int n = a.length;

int sum = 0;
for (int i = 0; i < a.length; i++) {
sum += a[n] * b[n];
}

System.out.println(sum);
}
}

Answer

n isn't the loop control variable, it's a.length which is an out of bounds index. You probably meant

sum += a[i] * b[i];

And, although it does not matter directly, you probably meant your for-loop to be

for (int i = 0; i < n; i++)

(I would assume that's the reason you have n in the first place.)

Comments