Write a method static int [][] pr (int [] v) that returns a 2D array consisting of all the pairwise products
of the elements of v. E.g., for a = {{2, 3, 1} the method returns 2D array b = {{4, 6, 2}, {6, 9, 3}, {2, 3, 1}}. Please note: This is an 2010 exam question, taken from Software and Programming 1 module.
public class ETenBTwoD
{
public static int [] [] pr (int [] v)
{
int [] a = {2, 3, 1};
int [][] b = {{0, 0, 0},{0, 0, 0}, {0, 0, 0}};
for (int i = 0; i<a.length; i++)
{
a[i] = a[i] * a[i];
}
return a;
}
}
I am not sure how to do this. Help will be appreciated. Thanks
The key is to use a nested loop. As you can see v[i] takes the first number (choosen by the first loop) and multiplies it by all the numbers in v (parameter array) since j has to increment the full length of v. The first loop then picks out the second number and the second loop does it again. In b[i][j] the i represents the current number we are calculating pairwise products for.