-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCodeathon_Question.java
More file actions
95 lines (93 loc) · 2.87 KB
/
Copy pathCodeathon_Question.java
File metadata and controls
95 lines (93 loc) · 2.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/* Write a program to create two matrices of (any input size/dimension M*N) and print results
of addition, subtraction and multiplication. Check and validate the dimension for each of
the operation. For example: If dimensions of two matrices are not same, the addition can not
be performed. So, if this situation occurs you have to print “Dimensions of matrices should be
same”. */
import java.util.*;
class Main
{
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
System.out.print("Enter no. of rows of 1st Matrix: ");
int m=in.nextInt();
System.out.print("Enter no. of columns of 1st Matrix: ");
int n=in.nextInt();
int[][] a=new int[m][n];
int[][] sum=new int[m][n];
int[][] diff=new int[m][n];
System.out.println("Enter the elements of 1st Matrix: ");
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
a[i][j]=in.nextInt();
}
}
System.out.print("Enter no. of rows of 2nd Matrix: ");
int M=in.nextInt();
System.out.print("Enter no. of columns of 2nd Matrix: ");
int N=in.nextInt();
int[][] b=new int[M][N];
System.out.println("Enter the elements of 2nd Matrix: ");
for(int i=0;i<M;i++)
{
for(int j=0;j<N;j++)
{
b[i][j]=in.nextInt();
}
}
System.out.println("Addition of two Matrices is:");
if(M!=m && N!=n)
{
System.out.println("Dimensions of matrices should be same.");
}
if(M==m && N==n)
{
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
sum[i][j]=a[i][j]+b[i][j];
System.out.print(sum[i][j]+" ");
}
System.out.println();
}
}
System.out.println("Subtraction of two Matrices is:");
if(M!=m && N!=n)
{
System.out.println("Dimensions of matrices should be same.");
}
if(M==m && N==n)
{
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
diff[i][j]=a[i][j]-b[i][j];
System.out.print(diff[i][j]+" ");
}
System.out.println();
}
}
int[][] mul=new int[m][N];
System.out.println("Multiplication of two Matrices is:");
if(m==n || n==M)
{
for(int i=0;i<m;i++)
{
for(int j=0;j<N;j++)
{
mul[i][j]=0;
for(int k=0;k<n;k++)
{
mul[i][j]=mul[i][j]+a[i][k]*b[k][j];
}
System.out.print(mul[i][j]+" ");
}
System.out.println();
}
}
}
}