Design and implement a Java program for programming exercise 8.5, page 306 (name
ID: 3737123 • Letter: D
Question
Design and implement a Java program for programming exercise 8.5, page 306 (name it AddMatricies) as described in the problem statement. Write method addMatrix() as specified. To test this method, the main method of your program prompts the user to enter two matrices that have the same dimensions, and then display their sum as shown in the sample run. The method addMatrix() must be designed to handle two-
dimensional arrays with any number of rows and columns. Design the main method of your program to handle all input
and output (following the model shown in the textbook) and to allow the user to re-run the program with different sets of inputs (i.e., use a loop). Document your code and organize the output using appropriate formatting techniques.
8.5 (Algebra: add two matrices) Write a method to add two matrices. The header of the method is as follows: public static double[]C] addMatrix(double[]] a, doublel]] b)Explanation / Answer
AddMatricies.java
import java.util.Scanner;
public class AddMatricies {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
double m1[][] = new double[3][3];
double m2[][] = new double[3][3];
double sum[][] = new double[3][3];
System.out.println("Enter matrix1: ");
for(int i=0;i<m1.length;i++) {
for(int j=0;j<m1[i].length;j++) {
m1[i][j]=scan.nextDouble();
}
}
System.out.println("Enter matrix2: ");
for(int i=0;i<m1.length;i++) {
for(int j=0;j<m1[i].length;j++) {
m2[i][j]=scan.nextDouble();
}
}
sum = addMatrix(m1, m2);
System.out.println("The matrices are added as follows");
for(int i=0;i<m1.length;i++) {
for(int j=0;j<m1[i].length;j++) {
System.out.print(sum[i][j]+" ");
}
System.out.println();
}
}
public static double[][] addMatrix(double[][] a, double[][] b) {
double sum[][] = new double[3][3];
for(int i=0;i<a.length;i++) {
for(int j=0;j<a[i].length;j++) {
sum[i][j]=a[i][j]+b[i][j];
}
}
return sum;
}
}
Output:
Enter matrix1:
1 2 3 4 5 6 7 8 9
Enter matrix2:
0 2 4 1 4.5 2.2 1.1 4.3 5.2
The matrices are added as follows
1.0 4.0 7.0
5.0 9.5 8.2
8.1 12.3 14.2
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.