Saturday, January 31, 2015

Java program to add two matrix after getting data from keyboard

The java program given below is able to add two matrices after getting all data from the keyboard. After running the program, you will be asked to provide the number of rows for the first matrix and soon you will be asked to provide the number of columns.

After providing the number of rows and columns then you will asked to provide the data for the matrix. Soon the matrix will be displayed on the screen. Besides, you will be asked to provide the number of rows and columns of the second matrix. Again you will be asked to provide the data for the second matrix.

Again the second matrix will be displayed and the summation of those two matrices will be displayed.
adding two matrices,summation of matrices
import java.util.*;
public class Matrix{
 public static void main(String [] args){
  //creating scanner object
  Scanner input = new Scanner(System.in);

  //getting input for the number of rows
  System.out.print("Enter the number of Rows: ");
  int row = input.nextInt();

  //getting input for the number of columns
  System.out.print("Enter the number of Columns: ");
  int col = input.nextInt();

  //creating double array
  int matrix[][] = new int[30][30];
  int matrix2[][] = new int[30][30];
  int sum[][] = new int[30][30];

  //getting input into the array
  System.out.print ("Enter data for first Matrix:\n");
  for(int i=1; i<=row; i++){
   for(int j=1; j<=col; j++){
    matrix[i][j] = input.nextInt();
   }
  }

  //displaying the first matrix
  System.out.println("The first matrix is:\n");
  for(int i=1; i<=row; i++){
   for(int j=1; j<=col; j++){
    System.out.print(matrix[i][j]+"    ");
   } System.out.print("\n\n\n");
  }

  //getting input into the array
  System.out.print ("Enter data for second Matrix:\n");
  for(int i=1; i<=row; i++){
   for(int j=1; j<=col; j++){
    matrix2[i][j] = input.nextInt();
   }
  }

  //displaying the second matrix
  System.out.println("The second matrix is:\n");
  for(int i=1; i<=row; i++){
   for(int j=1; j<=col; j++){
    System.out.print(matrix2[i][j]+"    ");
   } System.out.print("\n\n\n");
  }

  //adding two mattrix
  for(int i=1; i<=row; i++){
   for(int j=1; j<=col; j++){
    sum[i][j] = matrix[i][j] + matrix2[i][j];
   }
  }

  //displaying the summation
  System.out.println("The summation is:\n");
  for(int i=1; i<=row; i++){
   for(int j=1; j<=col; j++){
    System.out.print(sum[i][j]+"    ");
   } System.out.print("\n\n\n");
  }
 }
}


No comments:

Post a Comment