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);
}
}
nisn't the loop control variable, it'sa.lengthwhich is an out of bounds index. You probably meantAnd, although it does not matter directly, you probably meant your
for-loop to be(I would assume that's the reason you have
nin the first place.)