Please help with this programming assignment. Thanks a ton. Create a method for
ID: 3554258 • Letter: P
Question
Please help with this programming assignment. Thanks a ton.
Create a method for each of the operations given below. Each method should accept two 2D integer arrays (matrices) and return the result. The choice of operation should be taken from the user. The 2-D arrays can be declared and initialized in the main method itself (no need of user input).
1. Addition
1 2 + 2 5 = 3 7
1 5 4 3 = 5 8
2. Subtraction
1 2 - 2 5 = -1 -3
1 5 4 3 = -3 2
3. Multiplication
1 2 * 2 5 = 2 10
1 5 4 3 = 4 15
Explanation / Answer
import java.io.*;// to activate or open input-output package
class c1// class declaration
{
void add(int[][]a1,int[][]a2 )
{
int i,j;
int a3[][]= new int[a1.length][a1[0].length];
System.out.println("After addition of two matrices");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
a3[i][j]=a1[i][j]+a2[i][j];
System.out.print(a3[i][j]+" ");
}
System.out.print(" ");
}
}
void sub(int[][]a1,int[][]a2 )
{
int i,j;
int a3[][]= new int[a1.length][a1[0].length];
System.out.println("After Subtraction of two matrices");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
a3[i][j]=a1[i][j]-a2[i][j];
System.out.print(a3[i][j]+" ");
}
System.out.print(" ");
}
}
void mul(int[][]a1,int[][]a2 )
{
int i,j;
int a3[][]= new int[a1.length][a1[0].length];
System.out.println("After multiplication of two matrices");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
a3[i][j]=a1[i][j]*a2[i][j];
System.out.print(a3[i][j]+" ");
}
System.out.print(" ");
}
}
public static void main(String a[])throws IOException //start of the main function//
{
DataInputStream obj = new DataInputStream(System.in); //obj is the object of class DataInputStream used to assign the value from keyboard to RAM//
c1 obj1=new c1();
int a1[][]=new int[][]{{4,2,3},{6,2,5},{1,7,2}};
int a2[][]=new int[][]{{3,8,1},{2,4,7},{3,6,3}};
int ch;
System.out.println("Enter Your Choice 1-Add 2-Subtract 3-Multiply ");
ch=Integer.parseInt(obj.readLine());
int i,j;
System.out.println("First matrix is");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
System.out.print(a1[i][j]+" ");
}
System.out.print(" ");
}
System.out.println("Second matrix is ");
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
System.out.print(a2[i][j]+" ");
}
System.out.print(" ");
}
while(ch==1|| ch==2 || ch==3)
{
switch(ch)
{
case 1:
{
obj1.add(a1,a2);
break;
}
case 2:
{
obj1.sub(a1,a2);
break;
}
case 3:
{
obj1.mul(a1,a2);
break;
}
default:System.out.println("Invalid choice");
}
System.out.println("Enter Your Choice 1-Add 2-Subtract 3-Multiply ");
ch=Integer.parseInt(obj.readLine());
}
}
}