Sunday 28 August 2016

Chapter 8 Exercise 5, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

8.5 (Algebra: add two matrices) Write a method to add two matrices. The header of the method is as follows:
public static double[][] addMatrix(double[][] a, double[][] b)

In order to be added, the two matrices must have the same dimensions and the same or compatible types of elements. Let c be the resulting matrix. Each element  is +bij. For example, for two 3 * 3 matrices a and b, c is


Write a test program that prompts the user to enter two 3 * 3 matrices and displays their sum. Here is a sample run:

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    2.0    3.0    0.0    2.0    4.0    1.0 4.0 7.0 
4.0    5.0    6.0  + 1.0    4.5    2.2  = 5.0 9.5 8.2 
7.0    8.0    9.0    1.1    4.3    5.2    8.1 12.3 14.2  



import java.util.Scanner;
 
 
 
public class ProgramingEx8_5 {
 
 public static void main(String[] args) {
  double[][] a = new double[3][3];
  double[][] b = new double[3][3];
  double[][] result;
 
  java.util.Scanner input = new Scanner(System.in);
  System.out.print("Enter matrix1:");
  for (int i = 0; i < a.length; i++) {
   for (int j = 0; j < a[0].length; j++) {
    a[i][j] = input.nextDouble();
   }
 
  }
 
  System.out.print("Enter matrix2:");
  for (int i = 0; i < b.length; i++) {
   for (int j = 0; j < b[0].length; j++) {
    b[i][j] = input.nextDouble();
   }
 
  }
 
  result = addMatrix(a, b);
 
  // printing
  System.out.println("The matrices are added as follows");
  for (int i = 0; i < result.length; i++) {
   for (int j = 0; j < result[0].length; j++) {
 
    System.out.print(a[i][j] + " ");
    if (i == 1 && j == 2) {
     System.out.print(" + ");
    } else {
     System.out.print("   ");
    }
   }
   for (int j = 0; j < result[0].length; j++) {
    System.out.print(b[i][j] + " ");
    if (i == 1 && j == 2) {
     System.out.print(" = ");
    } else {
     System.out.print("   ");
    }
   }
   for (int j = 0; j < result[0].length; j++) {
    System.out.print(result[i][j] + " ");
   }
   System.out.println();
  }
 
 }
 
 public static double[][] addMatrix(double[][] a, double[][] b) {
  // Check metrix dimension
  if (a.length != b.length || a[0].length != b[0].length)
   return null;
 
  double[][] result = new double[b.length][a[0].length];
 
  for (int i = 0; i < result.length; i++) {
   for (int j = 0; j < result[0].length; j++) {
    result[i][j] = a[i][j] + b[i][j];
   }
 
  }
 
  return result;
 
 }
 
}

No comments :

Post a Comment