-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAddTwoMatrix.java
More file actions
78 lines (66 loc) · 2.05 KB
/
AddTwoMatrix.java
File metadata and controls
78 lines (66 loc) · 2.05 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
/*
* PROGRAM : To add two matrices using your own method. Print the resultant along with two input matrices.
* FILE : AddTwoMatrix.java
* CREATED BY : Santosh Hembram
* DATE : 12-10-20
*/
import java.util.*;
class Matrix{
public int[][] addMatrix(int arr[][],int arr2[][],int r,int c) {
int addResult[][] = new int[r][c];
for(int i=0; i<r; i++) {
for (int j=0; j<c; j++) {
addResult[i][j] = arr[i][j] + arr2[i][j];
}
}
return addResult;
}
}
class AddTwoMatrix {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the row size: ");
int r = sc.nextInt();
System.out.print("Enter the coloumn size: ");
int c = sc.nextInt();
int arr[][] = new int[r][c];
System.out.println("---------- Enter the elements of the 1st array --------------");
for(int i=0; i<r; i++) {
for (int j=0; j<c; j++) {
System.out.print("Enter the elements for row "+i+" coloumn "+j+": ");
arr[i][j] = sc.nextInt();
}
}
int arr2[][] = new int[r][c];
System.out.println("--------- Enter the elements of the 2nd array --------------");
for(int k=0; k<r; k++) {
for (int l=0; l<c; l++) {
System.out.print("Enter the elements for row "+k+" coloumn "+l+": ");
arr2[k][l] = sc.nextInt();
}
}
System.out.println("------- Displaying the 1st Matrix ----------");
for( int i=0; i<r; i++) {
for ( int j=0; j<c; j++) {
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
System.out.println("------- Displaying the 2nd Matrix ----------");
for( int k=0; k<r; k++) {
for ( int l=0; l<c; l++) {
System.out.print(arr2[k][l]+" ");
}
System.out.println();
}
Matrix obj = new Matrix();
int result[][] = obj.addMatrix(arr,arr2,r,c);
System.out.println("--------- After adding the two Matrix -------------");
for(int k=0; k<r; k++) {
for (int l=0; l<c; l++) {
System.out.print(result[k][l]+" ");
}
System.out.println();
}
}
}