Powered by Blogger.

Addition or Sum of 2x2 matrix using Arrays in java

>> Sunday, May 5, 2013

We know that arrays are different types, as usual one dimensional array, two dimensional array, three and multi (mxn) dimensional arrays.
In two dimensional arrays we need 2x2 array.

A 2x2 matrix is a rectangular often square array of numbers having 2 columns and 2 rows, or expressions which can be evaluated to numbers. The dimensions m x n refer to the number of rows (m) and columns (n) respectively.

We can declare the one dimensional array as:
int[] myArray = {0,1,2,3};
and two dimensional array looks like this:
 int[][] myArray = { {0,1,2,3}, {3,2,1,0}, {3,5,6,1}, {3,8,3,4} };


this array size is 4X4. Here in our program we are using 2X2 array only. Let us take two arrays named as A(2X2) and B(2X2), then add these two arrays. The resultant array(matrix) named as C(2X2).
A general formula shown below notice that the indices match for the elements that combine, and that matrix addition and subtraction is commutative; e.g (A + B = B + A).
In the below program we are taking a and b two two dimensional arrays(A and B matrix). Take a resultant matrix C assign the resultant value from A+B.
c[i][j]=a[i][j]+b[i][j];

package blog.javabynataraj;
/*Addition of two dimentional arraylist
 * http://www.javabynataraj.blogspot.com */
class MatrixAddition
{
 public static void main(String[] args) 
 {
  int a[][]={ {67,89},
     {56,78}
      };
         int b[][]={ {7,9},
      {6,8}
       };
           int c[][]=new int[2][2];

     System.out.println(" \n First Array values are ");
     for(int i=0;i<a.length;++i)
     {
      System.out.println();
      for(int j=0;j<a[i].length;++j)
       System.out.print("\t"+a[i][j]);
     }//end of for
     System.out.println("\n Second Array values are ");
     for(int i=0;i<b.length;++i)
     {
      System.out.println();
      for(int j=0;j<b[i].length;++j)
       System.out.print("\t"+b[i][j]);
     }//end of for
     for(int i=0;i<a.length;++i)
     for(int j=0;j<b.length;++j)
     c[i][j]=a[i][j]+b[i][j];
          System.out.println("\n Addition of two arrays values are ");
     for(int i=0;i<c.length;++i)
     {
      System.out.println();
      for(int j=0;j<c[i].length;++j)
       System.out.print("\t"+c[i][j]);
     }//end of for
 }//end of main
}//end of class

If you are trying to compile this program in your command prompt you should know how to compile a packaged program. you can use this if you not find in the above link:
javac -d . ClassName.java
Output:
 

Related Posts Plugin for WordPress, Blogger...
© javabynataraj.blogspot.com from 2009 - 2022. All rights reserved.