Multiplication of vectors A and B resulting in matrix C

0

I have a Java exercise here to solve but I can not understand exactly what I need to do, if anyone can give me an explanation, thank you! I need to do the following:

Given the A = [1,2,3,4,5] and B = [1,2,3,4,5] vectors, create algorithms to generate an array C of the multiplication of the elements of A by the elements of B. Notice that

C[1,1] <- A[1,1] * B[1,1]
C[1,2] <- A[1,1] * B[1,2]
C[1,3] <- A[1,1] * B[1,3] 
...
    
asked by anonymous 04.06.2017 / 21:36

1 answer

4

You need to use two interleaved loops to do this type of operation: the outermost will fill rows of the resulting array, while moving the items of the first array (vetA), the second will populate columns of the resulting array, while moving items from the second array (vetB):

The code looks like this:

int[] vetA = {1,2,3,4,5};
int[] vetB = {1,2,3,4,5};
int[][] mat =  new int[5][5];

for(int i = 0; i < vetA.length;i++){
    for(int j = 0; j < vetB.length; j++){
        mat[i][j] = vetA[i] * vetB[j];
    }
}

for(int i = 0; i < mat[0].length; i++){
    for(int j = 0; j < mat.length;j++ ){
        System.out.print(mat[i][j] + " ");
    }
    System.out.println();
}

Result:

1 2 3 4 5 
2 4 6 8 10 
3 6 9 12 15 
4 8 12 16 20 
5 10 15 20 25

See working at ideone: link

Note that because we have a multiplication that will result in a square matrix, you can use the same combination to display on the screen.

    
04.06.2017 / 21:52