Write a Java program that will use a two-dimensional array and perform the follo
ID: 3763594 • Letter: W
Question
Write a Java program that will use a two-dimensional array and perform the following operations in order:
Create two 2-dim arrays/matrices (random numbers, range 1 - 500, where 1 and 500 should be declared as class constants). Both have the same dimensions.
Print the arrays.
Call a method to sum the 2 matrices. The sum of 2 matrices matrix_1 and matrix_2 is a matrix result, where for every row r and column c,
resultrc = matrix_1rc + matrix_2rc.
Print the resulting matrix.
The program will include a loop (count controlled or sentinel controlled, your choice); inside the loop call the required methods. Use dynamic arrays and make sure you do input validation.
Explanation / Answer
import java.util.Random;
/**
* @author Srinivas
*
*
*/
public class MatrxAddition {
final static int min = 1, max = 500;
public static void main(String args[]) {
int[][] matrixA, matrixB, matrix;
matrixA = getRandomMatrix(2, 2);
matrixB = getRandomMatrix(2, 2);
System.out.println("Matrix A:");
printRandomMatrix(matrixA);
System.out.println("Matrix B:");
printRandomMatrix(matrixB);
matrix = sumRandomMatrix(matrixA, matrixB);
System.out.println("Matrix Sum A and B:");
printRandomMatrix(matrix);
}
/**
* @param row
* @param col
* @return
*/
public static int[][] getRandomMatrix(int row, int col) {
// int random = new Random().nextInt(range + 1) + min;
int randomMatrix[][] = new int[row][col];
Random rand = new Random();
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
randomMatrix[i][j] = rand.nextInt((max - min) + 1) + min;
}
}
return randomMatrix;
}
/**
* @param randomMatrix
* @return
*/
public static int[][] printRandomMatrix(int[][] randomMatrix) {
for (int i = 0; i < randomMatrix.length; i++) {
for (int j = 0; j < randomMatrix[i].length; j++) {
System.out.print(randomMatrix[i][j] + " ");
}
System.out.println();
}
return randomMatrix;
}
/**
* @param matrixA
* @param matrixB
* @return
*/
public static int[][] sumRandomMatrix(int[][] matrixA, int[][] matrixB) {
int[][] matrix = new int[matrixA.length][matrixA.length];
for (int i = 0; i < matrixA.length; i++) {
for (int j = 0; j < matrixA[i].length; j++) {
matrix[i][j] = matrixA[i][j] + matrixB[i][j];
}
System.out.println();
}
return matrix;
}
}
OUTPUT :
Matrix A:
111 249
83 147
Matrix B:
93 174
232 28
Matrix Sum A and B:
204 423
315 175
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.