In: Computer Science
Using Java:
Implement print2D(A) so that it prints out its 2D array argument A in the matrix form.
Implement add2Ds(A,B) so that it creates and returns a new 2D array C such that C=A+B.
Implement multiScalar2D(c,A) so that it creates and returns a new 2D array B such that
B=c×A.
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 following:A=
1234 5678 9 10 11 12
B=
2468 10 12 14 16 18 20 22 24
A+B=
3 6 9 12 15 18 21 24 27 30 33 36
5XA=
51015 20 25 30 35 40 45 50 55 60
Transpose of A =
159 2 6 10 3 7 11 4 8 12
Note that your methods should work for 2D arrays of any sizes.
If you have any doubts, please give me comment...
public class Matrix{
public static void main(String[] args) {
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=");
print2D(A);
System.out.println("\nB=");
print2D(B);
int[][] C = add2D(A, B);
System.out.println("\nA+B=");
print2D(C);
B = multiScalar(5, A);
System.out.println("\n5XA=");
print2D(B);
B = transpose2D(A);
System.out.println("\nTranspose of A=");
print2D(B);
}
public static void print2D(int[][] A){
for(int i=0; i<A.length; i++){
for(int j=0; j<A[i].length; j++){
System.out.printf("%3d", A[i][j]);
}
System.out.println();
}
}
public static int[][] add2D(int[][] A, int[][] B){
int rows = A.length;
int cols = A[0].length;
int result[][] = new int[rows][cols];
for(int i=0; i<rows; i++){
for(int j=0; j<cols; j++){
result[i][j] = A[i][j] + B[i][j];
}
}
return result;
}
public static int[][] multiScalar(int c, int[][] A){
int rows = A.length;
int cols = A[0].length;
int result[][] = new int[rows][cols];
for(int i=0; i<rows; i++){
for(int j=0; j<cols; j++){
result[i][j] = c*A[i][j];
}
}
return result;
}
public static int[][] transpose2D(int[][] A){
int rows = A.length;
int cols = A[0].length;
int result[][] = new int[cols][rows];
for(int i=0; i<rows; i++){
for(int j=0; j<cols; j++){
result[j][i] = A[i][j];
}
}
return result;
}
}