Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

l you exercises with using two dimensional arrays of Java and practices with usi

ID: 3885537 • Letter: L

Question

l you exercises with using two dimensional arrays of Java and practices with using

methods that return arrays. What you should do is to download and complete the instructor’s

program lab03.java:

1. Implement print2D(A) so that it prints out its 2D array argument A in the matrix form.

2. Implement add2Ds(A,B) so that it creates and returns a new 2D array C such that C=A+B.

3. Implement multiScalar2D(c,A) so that it creates and returns a new 2D array B such that

B=c×A.

4. Implement transpose2D(A), which creates and returns a new 2D array B such that B is

the transpose of A.Your output should look like the follow g:in

A =

1   2 3 4

5   6 7 8

9   10 11 12

B =

2 4 6 8

10 12 14 16

18 20 22 24

A + B =

3 6 9 12

15 18 21 24

27 30 33 36

5 X A =

5 10 15 20

25 30 35 40

45 50 55 60

Transpose of A =

1 5 9

2 6 10

3 7 11

4 8 12

Note that your methods should work for 2D arrays of any sizes

Explanation / Answer

import java.io.*;

public class DemoMatrix{

   public static void print2D(int A[][], int m,int n){
        for (int i = 0; i<m; i++){
           for(int j = 0; j<n; j++){
              System.out.print(A[i][j] + " ");
           }
           System.out.println();
        }
   }
   public static int[][] add2D(int A[][], int B[][]){
        int[][] C = new int[3][4];

        for (int i = 0; i<3; i++){
           for(int j = 0; j<4; j++){
              C[i][j] = A[i][j] + B[i][j];
           }
          
        }
        return C;
   }
   public static int[][] multiScalar(int c,int A[][]){
        int[][] C = new int[3][4];

        for (int i = 0; i<3; i++){
           for(int j = 0; j<4; j++){
              C[i][j] = c * A[i][j];
           }
          
        }
        return C;
   }
   public static int[][] transpose(int A[][]){
        int[][] C = new int[4][3];

        for (int i = 0; i<4; i++){
           for(int j = 0; j<3; j++){
              C[i][j] = A[j][i];
           }
        }
        return C;
   }


   public static void main(String[] args){
       int[][] C;

       int A[][] = {{1,2,3,4},
            {5,6,7,8},
            {9,10,11,12}};

       int B[][] = {{2,4,6,8},
            {10,12,14,16},
            {18,20,22,24}};

       System.out.println("A + B =");
       print2D(add2D(A,B),3,4);
       System.out.println("5 X A =");
       print2D(multiScalar(5,A),3,4);
       System.out.println("Transpose of A =");
       print2D(transpose(A),4,3);
      
   }
}