Tuesday 15 March 2016

Simple addition using matrix in java

Matrix addition is also possible in java. The following code explains the matrix addition.



import java.io.*;

class matadd

{

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

{
/*declaration of variables and arrays*/


int i,n,m,j,x,y;

int a[][]=new int [10][10];

int b[][]=new int [10][10];

int c[][]=new int [10][10];

           

DataInputStream br =new DataInputStream(System.in);


/*Getting the number of rows and columns for A and B matrices*/ 


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

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



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

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



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

x=Integer.parseInt (br.readLine());



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

y=Integer.parseInt (br.readLine());


/*Checking whether the matrices are with same order */


if((m==x)&&(n==y))

{

  System.out.println("Enter the A array Elements");

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

  {

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

    {

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

    }

  }

  System.out.println("Enter the B array Elements");

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

  {

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

   {

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

   }

  }

/*addition of the two matrices*/            

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

  {

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

    {

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

    }

  }
/*printing of the answer in the form of a matrix*/

  System.out.println("Answer");

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

  {

    System.out.println("\t\n");

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

    {

  System.out.println(c[i][j]);

  System.out.println("\t");

    }

    }

}

else

{

   System.out.println("Matrix Addition can not be performed for the given rows and columns of the matrices");

}

}

}



Output :



H:\>javac matadd.java

H:\>java matadd

Enter the number of rows for A

3

Enter the number of columns for A

3

Enter the number of rows for B

3

Enter the number of columns for B

3




Enter the A array Elements                                                               
1

2

3

4

5

6

7

8

9



Enter the B array Elements

1

2

3

4

5

6

7

8

9



Answer

2

4

6



8

10

12



14

16

18




No comments:

Post a Comment