Wednesday, 23 November 2016

Matrix addition

This program show how to add two matrices A & B into a third matrix C. Here the matrix having 3 rows and 3 columns (3x3). As given below, inputMatrix( ) and displayMatrix( ) are two static methods which are used to read and display the matrix values respectively. java.util.Scanner class is used to read values from keyboard at runtime.


PROGRAM
import java.util.Scanner;

class MatrixAddition {

 public static void inputMatrix(int temp[][]) {
  Scanner s = new Scanner(System.in);
  for(int i=0;i<3; i++) {
   for(int j=0; j<3; j++) {
    temp[i][j] = s.nextInt();
   }
  }
 }
 
 public static void displayMatrix(int temp[][]) {
  for(int i=0;i<3; i++) {
   for(int j=0; j<3; j++) {
    System.out.print(temp[i][j] + " ");
   }
   System.out.println("");
  }
 }
 
 public static void main(String[] args) {

  int a[][] = new int[3][3];  // First matrix
  int b[][] = new int[3][3];  // Second matrix
  int c[][] = new int[3][3];  // Final matrix which is to store addition
  
  // Input Matrix A elements
  System.out.println("Enter the 9 numbers for first matrix (3x3)...");
  inputMatrix(a);
  
  // Input Matrix B elements
  System.out.println("Enter the 9 numbers for second matrix (3x3)...");
  inputMatrix(b);
  
  // Addition logic goes here
  for(int x=0; x<3; x++) {
   for(int y=0; y<3; y++) {
    c[x][y] = a[x][y] + b[x][y]; 
   }
  }
  
  System.out.println("Matrix A is ...");
  displayMatrix(a);
  
  System.out.println("Matrix B is ...");
  displayMatrix(b);
  
  System.out.println("After addition Matrix C is ...");
  displayMatrix(c);
 }

}
OUTPUT
C:\>javac MatrixAddition.java
C:\>java MatrixAddition
Enter the 9 numbers for first matrix (3x3)...
1 2 3
4 5 6
7 8 9
Enter the 9 numbers for second matrix (3x3)...
1 2 3
4 5 6
7 8 9
Matrix A is ...
1 2 3 
4 5 6 
7 8 9 
Matrix B is ...
1 2 3 
4 5 6 
7 8 9 
After addition Matrix C is ...
2 4 6 
8 10 12 
14 16 18 

No comments:

Post a Comment