Java Program

Object:-Write a Program for Addition of two Matrices

import java.util.Scanner; //import Scanner class in our program

class demo
{
 public static void main(String…s)
   {
    int i,j,n,m;
    Scanner sc=new Scanner(System.in); //used to read from keyboard

    System.out.print(“Enter number of rows:”);
    m=sc.nextInt();
    System.out.print(“Enter number of columns:”);
    n=sc.nextInt();

   int a1[][]=new int[m][n];
   int a2[][]=new int[m][n];
   int a3[][]=new int[m][n];

   System.out.print(“nEnter elements of first matrix:n”);
   for(i=0;i<m;++i)
   for(j=0;j<n;++j)

   a1[i][j]=sc.nextInt();
   System.out.print(“nEnter elements of second matrix:n”);
   for(i=0;i<m;++i)
   for(j=0;j<n;++j)

   a2[i][j]=sc.nextInt();
   System.out.print(“nAddition of Matrices:n”);
   for(i=0;i<m;++i)
    {
     for(j=0;j<n;++j)
      {
       a3[i][j]=a1[i][j]+a2[i][j];
       System.out.print(a3[i][j]+” “);
     }
   System.out.print(“n”);
  }

 }

}

Output

Enter number of rows:2
Enter number of columns:2
Enter elements of first matrix:
1 2
 

Explanation

In this Program,We have find out the sum of two matrix.








You may also like: