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

1) Write a Java program that fills a 3x4 matrix with random numbers in (0, 9] an

ID: 3607307 • Letter: 1

Question

1) Write a Java program that fills a 3x4 matrix with random numbers in (0, 9] and calculates the sum of the elements in each row. For example: 0 32 71sum 12 6031| 5148] - - sum·10 sum·18 Use a two-dimensional array to store the matrix elements. 2) Write a Java program that adds two 4x4 matrices and prints the resulting matrix. For example: [0 1 27 [1 10 2 [1 2 2 9 3120 3 267 6 3 8 7 5 1 44 4 03 2 9 1 7 6 Use two-dimensional arrays to store the elements of the matrices. Your program should initialize the matrices in the declaration line.

Explanation / Answer

MatrixWithRandNos.java

import java.util.Random;

public class MatrixWithRandNos {
public static void main(String[] args) {
// Declaring variables
int rows = 3;
int cols = 4;

// Creating a 2-D Matrix
int Matrix[][] = new int[rows][cols];

// Creating a random Class object
Random r = new Random();

// Initialize the matrix elements with random numbers
for (int i = 0; i < rows; i++) {
for (int j = 0; j < rows; j++) {
Matrix[i][j] = r.nextInt((9) + 1);
}
}

int tot = 0;
// Displaying the matrix and find the sum of each row and display
for (int i = 0; i < rows; i++) {
tot = 0;
for (int j = 0; j < cols; j++) {
tot += Matrix[i][j];
System.out.print(Matrix[i][j] + " ");
}
System.out.print(" Sum=" + tot);
System.out.println();
}

}

}

________________

Output:

6 3 9 0 Sum=18

9 1 9 0 Sum=19

6 5 5 0 Sum=16

_______________

2)

MatrixAddition.java

public class MatrixAddition {

public static void main(String[] args) {

//Declaring two matrices and initialization

int Matrix1[][]={{0,1,2,7},{6,0,3,1},{3,1,2,0},{5,1,4,4}};

int Matrix2[][]={{1,1,0,2},{3,4,5,0},{3,2,6,7},{4,0,3,2}};

//Creating an 2-D Matrix
int result[][] = new int[Matrix1.length][Matrix1[0].length];

//Performing addition
for (int i = 0; i < Matrix1.length; i++) {
for (int j = 0; j < Matrix1[0].length; j++) {
result[i][j] = Matrix1[i][j] + Matrix2[i][j];
}
}

display(Matrix1, Matrix2, result);
}
//This method will display the output
private static void display(int[][] matrix1, int[][] matrix2,
int[][] matrix3) {
char ch = '+';
for (int i = 0; i < matrix1.length; i++) {
for (int j = 0; j < matrix1[0].length; j++) {
System.out.print(matrix1[i][j] + " ");

}
if (i == 1)
System.out.print(" " + ch + " ");
else
System.out.print(" ");
for (int j = 0; j < matrix1[0].length; j++) {
System.out.print(matrix2[i][j] + " ");

}
if (i == 1)
System.out.print(" = ");
else
System.out.print(" ");
for (int j = 0; j < matrix1[0].length; j++) {
System.out.print(matrix3[i][j] + " ");
}
System.out.println(" ");
}

}

}

_____________________

OUtput:

0 1 2 7 1 1 0 2 1 2 2 9   
6 0 3 1 + 3 4 5 0 = 9 4 8 1   
3 1 2 0 3 2 6 7 6 3 8 7   
5 1 4 4 4 0 3 2 9 1 7 6   

________Could you rate me well.Plz .Thank You