Monday, October 22, 2012

Matrix in Java

Program for matrix in java is as follows:


import java.io.*;

class matrix
{
  int mat[][],r,c;

  matrix()
  {
     mat = new int[10][10];
  }
  public void getMat() throws Exception
  {
   // mat = new int[10][10];
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("\nEnter the Dim of the matrix : ");    
    r = Integer.parseInt(br.readLine());
    c = Integer.parseInt(br.readLine());

    System.out.println("\nEnter the matrix elements : ");    
    for(int i = 0 ; i < r ; i++)
    {
      for(int j = 0 ; j < c ; j++)
      {
        mat[i][j] = Integer.parseInt(br.readLine());
      }
    }
  }

  public void addMat(matrix m1,matrix m2)
  {
     r = m1.r;
     c = m1.c;

     for(int i = 0 ; i < r ; i++)
    {
       for(int j = 0 ; j < c ; j++)
       {
          mat[i][j] = m1.mat[i][j] + m2.mat[i][j];
       }
    }
  }

  public void putMat()
  {
    System.out.println("\nMatrix is : \n");
    for(int i = 0 ; i < r ; i++)
    {
      for(int j = 0 ; j < c ; j++)
      {
        System.out.print(" " + mat[i][j]);
      }
      System.out.println("");
    }
  }

  public static void main(String args[]) throws Exception
  {
    matrix m1 = new matrix();
    matrix m2 = new matrix();
    matrix m3 = new matrix();

    m1.getMat();
    m2.getMat();

    m1.putMat();
    m2.putMat();

    m3.addMat(m1,m2);
    m3.putMat();
  } 
}

No comments:

Post a Comment

MS SQL : How to identify fragmentation in your indexes?

Almost all of us know what fragmentation in SQL indexes are and how it can affect the performance. For those who are new Index fragmentation...