Addition and Multiplication on matrix

addition and multiplication on matrix

Java program to perform addition and multiplication on matrix

In this post, we will learn how to perform matrix operations like matrix addition and matrix multiplication of a matrix using java. Let’s start with how to create the matrix in java.

import java.io.*;
class MatrixDemo
{
public static void main(String args[]) throws IOException
{
int x,y,i,j,k;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter the number of rows of matrix: ");
x=Integer.parseInt(br.readLine());
System.out.print("Enter the number of columns of matrix: ");
y=Integer.parseInt(br.readLine());
int a[][] = new int[x][y];
int b[][] = new int[x][y];
int c[][] = new int[x][y];
System.out.println("Enter the elements of first matrix: ");
for(i=0;i<x;i++)
{
for(j=0;j<n;j++)
{
a[i][j]=Integer.parseInt(br.readLine());
}
} 
System.out.println("Enter the elements of second matrix: ");
for(i=0;i<x;i++)
{
for(j=0;j<y;j++)
{
b[i][j]=Integer.parseInt(br.readLine());
}
}
for(i=0;i<x;i++)
{
for(j=0;j<y;j++)
{
c[i][j]=a[i][j]+b[i][j]; 
}
}
System.out.println("Addition of two matrices is: ");
for(i=0;i<x;i++)
{
for(j=0;j<y;j++)
{
System.out.print(c[i][j]+"\t");
}
System.out.println();
}
for(i=0;i<x;i++)
{
for(j=0;j<y;j++)
{
c[i][j]=0;
for(k=0;k<x;k++)
{
c[i][j]=c[i][j]+(a[i][k]*b[k][j]); 
}
}
}
System.out.println("Multiplication of two matrices is: ");
for(i=0;i<x;i++)
{
for(j=0;j<y;j++)
{
System.out.print(c[i][j]+"\t");
}
System.out.println();
}
}
}

Program Output:

Enter the number of rows of matrix: 2
Enter the number of columns of matrix: 2
Enter the elements of first matrix:
1
3
4
5
Enter the elements of second matrix:
6
7
8
9
Addition of two matrices is:
7      10
12    14
Multiplication of two matrices is:
30    34
64    73

I hope this post helps you to understand the addition and multiplication operation on the matrix and its implementation in Java programming language.

Keep coding 🙂

1 thought on “Addition and Multiplication on matrix”

Leave a Reply

Your email address will not be published. Required fields are marked *