forked from regression1607/HacktoberFest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
addmatrix.java
63 lines (51 loc) · 1.2 KB
/
addmatrix.java
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
// Java program for addition of two matrices
import java.io.*;
class GFG {
// Function to print Matrix
static void printMatrix(int M[][],
int rowSize,
int colSize)
{
for (int i = 0; i < rowSize; i++) {
for (int j = 0; j < colSize; j++)
System.out.print(M[i][j] + " ");
System.out.println();
}
}
// Function to add the two matrices
// and store in matrix C
static int[][] add(int A[][], int B[][],
int size)
{
int i, j;
int C[][] = new int[size][size];
for (i = 0; i < size; i++)
for (j = 0; j < size; j++)
C[i][j] = A[i][j] + B[i][j];
return C;
}
// Driver code
public static void main(String[] args)
{
int size = 4;
int A[][] = { { 1, 1, 1, 1 },
{ 2, 2, 2, 2 },
{ 3, 3, 3, 3 },
{ 4, 4, 4, 4 } };
// Print the matrices A
System.out.println("\nMatrix A:");
printMatrix(A, size, size);
int B[][] = { { 1, 1, 1, 1 },
{ 2, 2, 2, 2 },
{ 3, 3, 3, 3 },
{ 4, 4, 4, 4 } };
// Print the matrices B
System.out.println("\nMatrix B:");
printMatrix(B, size, size);
// Add the two matrices
int C[][] = add(A, B, size);
// Print the result
System.out.println("\nResultant Matrix:");
printMatrix(C, size, size);
}
}