Accept two n x m matrices. Write a Java program to find addition of these matrices.

in this java tutorial we are learn about addition of two matrix, both matrix having same size 
  • take two matrix to be added.
  • creating new matrix to store the addition of two matrix
  • traverse each element of the two matrices  and add them . store the sum of two matrix in new matrix at the corresponding index.
  • print the final new matrix. 
code:

import java.io.*;

class MathAddition

{

public static void main(String args[]) throws IOException

{

int m,n,i,j;

DataInputStream dis=new DataInputStream(System.in);

System.out.println("Enter the number of rows for matrix");

n=Integer.parseInt(dis.readLine());

System.out.println("Enter the number of columns for matrix");

m=Integer.parseInt(dis.readLine());

int a[][]=new int[n][m];

int b[][]=new int[n][m];

int c[][]=new int[n][m];

System.out.println("Enter elements for first"+n+"x"+m+"matrix");

for(i=0;i<n;i++)

{

for(j=0;j<m;j++)

{

a[i][j]=Integer.parseInt(dis.readLine());

}

}

System.out.println("Enter elements for second"+n+"x"+m+"matrix");

for(i=0;i<n;i++)

{

for(j=0;j<m;j++)

{

b[i][j]=Integer.parseInt(dis.readLine());

}

}

/*Performing Addition

System.out.println("Enter elements for first"+n+"r"+m+",matrix");

for(i=0;i<n;i++)

{

for(j=0;j<m;j++)

{

c[i][j]=a[i][j]+b[i][j]

}

}

/*Displaying the result*/

System.out.println("Enter elements for first"+n+"r"+m+"matrix");

for(i=0;i<n;i++)

{

for(j=0;j<m;j++)

{

System.out.print("c[i][j]+");

}

System.out.print("\n");

}

}

}

Output :


Post a Comment

0 Comments