Home > front end >  How do I use a loop to multiply a row of a 2D array to the column of a second 2D array, and etc in J
How do I use a loop to multiply a row of a 2D array to the column of a second 2D array, and etc in J

Time:11-19

So I'm learning Java for Uni, and one of the activities our teachers assigned us for homework was to multiply two 2D arrays in a specific way.

What he wants us to do.

I figured, similar to printing the contents of a 2D array, I could use a for loop to loop through both arrays and add/multiply as necessary. However, I've been scratching my head on how to do it.

I've tried doing this, but this gave me a totally different result.

for (int m=0; m<c.length; m  ){
    for (int n=0; n<c[m].length; n  ){
        c[m][n] = 0;
        for (int o=0; o<c.length; o  ){
            c[m][n]  = a[n][m]*b[m][n];
        };
    };
};

Result of code.

Writing down each one, and adding/multiplying as necessary seems to work:

c[0][0] = (a[0][0]*b[0][0])   (a[0][1]*b[1][0])   (a[0][2]*b[2][0]);
c[0][1] = (a[0][0]*b[0][1])   (a[0][1]*b[1][1])   (a[0][2]*b[2][1]);
c[0][2] = (a[0][0]*b[0][2])   (a[0][1]*b[1][2])   (a[0][2] * b[2][2]);
c[1][0] = (a[1][0]*b[0][0])   (a[1][1]*b[1][0])   (a[1][2]*b[2][0]);
c[1][1] = (a[1][0]*b[0][1])   (a[1][1]*b[1][1])   (a[1][2]*b[2][1]);
c[1][2] = (a[1][0]*b[0][2])   (a[1][1]*b[1][2])   (a[1][2] * b[2][2]);
c[2][0] = (a[2][0]*b[0][0])   (a[2][1]*b[1][0])   (a[2][2]*b[2][0]);
c[2][1] = (a[2][0]*b[0][1])   (a[2][1]*b[1][1])   (a[2][2]*b[2][1]);
c[2][2] = (a[2][0]*b[0][2])   (a[2][1]*b[1][2])   (a[2][2] * b[2][2]);

But it's pretty ugly to look at.

Am I wrong for thinking that I could use a for loop?

CodePudding user response:

you can do your work with this code :

        int size = 3;
        int [][] a = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        int [][] b = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        int [][] c = {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}};;
        
        int total;
        for(int i = 0; i < size; i  ) {
            for (int j = 0; j < size; j  ) {
                total = 0;
                for (int k = 0; k < size; k  ) {
                    total  = a[i][k] * b[k][j];
                }
                c[i][j] = total;
            }
        }
  • Related