Java program to find Sum, Transpose and matrix multiplication

Last updated:5th Nov 2021

In this program, you will write a java program to display 3x3 matrixes. Find the sum, multiplication, and transpose operation.

Program to find sum, multiplication, and transpose operation

import java.util.Scanner;
class Matrix
{
  public static void main(String args[])
  {
    int rowa, cola, rowb, colb, total=0, c, d, k;
 
    Scanner in = new Scanner(System.in);
    System.out.println("Enter the number of rows and columns of first matrix");
    rowa = in.nextInt();
    cola = in.nextInt();
 
    int first[][] = new int[rowa][cola];
 
    System.out.println("Enter elements of first matrix");
 
    for (c = 0; c < rowa; c++)
      for (d = 0; d < cola; d++)
        first[c][d] = in.nextInt();
 
    System.out.println("Enter the number of rows and columns of second matrix");
    rowb = in.nextInt();
    colb = in.nextInt();
    int second[][] = new int[rowb][colb];
    if (cola != rowb)
      System.out.println("The matrices can't be multiplied with each other.");
    else
    {
      int multiply[][] = new int[rowa][colb];
 
      System.out.println("Enter elements of second matrix");
 
      for (c = 0; c < rowb; c++)
        for (d = 0; d < colb; d++)
          second[c][d] = in.nextInt();
 
      for (c = 0; c < rowa; c++) {
        for (d = 0; d < colb; d++) {
          for (k = 0; k < rowb; k++)
            total = total + first[c][k]*second[k][d];
 
          multiply[c][d] = total;
          total = 0;
        }
      }
 
      System.out.println("Product of the matrices:");
 
      for (c = 0; c < rowa; c++) {
        for (d = 0; d < colb; d++)
          System.out.print(multiply[c][d]+"\t");
 
        System.out.print("\n");
      }
    }
	int sum[][]=new int[rowa][cola];
	for(c=0;c<rowa;c++)
	{ 
	  for(d=0;d<cola;d++)
	  {
		sum[c][d]=first[c][d]+second[c][d];
	  }
	}
	System.out.println("sum of the matrices:");
	for(c=0;c<rowa;c++){
	  for(d=0;d<cola;d++){
	   	System.out.print(sum[c][d]+"\t");
	  }
	  System.out.print("\n");
	}
	System.out.println("Transpos of the matrices:");
	for(c=0;c<cola;c++){
	  for(d=0;d<rowa;d++){
	   	System.out.print(sum[d][c]+"\t");
	  }
	  System.out.print("\n");
	}	
  }
}

output

C:\gaurav>javac Matrix.java
C:\gaurav>java Matrix
Enter the number of rows and columns of first matrix
3 3
Enter elements of first matrix
1 2 3
2 3 4
1 2 3
Enter the number of rows and columns of second matrix
3 3
Enter elements of second matrix
1 2 3
4 5 6
7 8 9
Product of the matrices:
30	36	42
42	51	60
30	36	42
sum of the matrices:
2	4	6
6	8	10
8	10	12
Transpos of the matrices:
2	6	8
4	8	10
6	10	12