write a java program to perform addition and substraction of two matrices.

 

write a java program to perform addition and substraction  of two matrices.


Program :

import java.util.*;
public class matrixopera
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the order of the matrix :");
int r=sc.nextInt();
int c=sc.nextInt();
int i, j, k;
int a[ ][ ]=new int[r][c];
int b[ ][ ]=new int[r][c];
int res[ ][ ]=new int[r][c];
System.out.println("Enter the elements for matrixA:");
for(i=0;i<r;i++)
{ for(j=0;j<c;j++)
{
a[i][j]=sc.nextInt();
}
}
System.out.println("Enter the elements for matrix B:");
for(i=0;i<r;i++)
{ for(j=0;j<c;j++)
{
b[i][j]=sc.nextInt();
}
}
//matrix addition
for(i=0;i<r;i++)
{ for(j=0;j<c;j++)
{
res[i][j]=a[i][j]+b[i][j];
}
}
System.out.println("Addition of  matrix :");
System.out.println("Resultant matrix is:");
for(i=0;i<r;i++)
{ System.out.println();
for(j=0;j<c;j++)
{
System.out.print(res[i][j]+"\t");
}
}
//matrix substraction
for(i=0;i<r;i++)
{ for(j=0;j<c;j++)
{
res[i][j]=a[i][j]-b[i][j];
}
}
System.out.println("\nsubstraction of  matrix :");
System.out.println("Resultant matrix is:");
for(i=0;i<r;i++)
{ System.out.println();
for(j=0;j<c;j++)
{
System.out.print(res[i][j]+"\t");
}
}
}
}


Output :


Enter the order of the matrix :
2  2
Enter the elements for matrixA:
1    2
3     4
Enter the elements for matrix B:
5     6
7     8
Addition of matrix:
Resultant matrix is:
6      8
10      12
substraction of  matrix :
Resultant matrix is:
-4       -4
-4       -4



Note :

The two matrix involving in addition and substraction operation must have same number of rows and columns.(order of matrices must be same).

Comments

Popular posts from this blog

Control Statements:Selection statement ,Iteration statement and Jump statement in Java

Java Database Connectivity (JDBC) ,Steps to connect to the database in Java

Applets - Inheritance hierarchy for applets, differences between applets and applications, life cycle of an applet, passing parameters to applets, applet security issues.