Java Program to add two Matrix:
package javaapplication22;
import java.util.Scanner;
public class AddTwoMatrix {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.print("Enter number of rows: ");
int rows = s.nextInt();
System.out.print("Enter number of columns: ");
int cols = s.nextInt();
int[][] a = new int[rows][cols];
int[][] b = new int[rows][cols];
System.out.println("Enter the first matrix");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
a[i][j] = s.nextInt();
}
}
System.out.println("Enter the second matrix");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
b[i][j] = s.nextInt();
}
}
int[][] c = new int[rows][cols];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
c[i][j] = a[i][j] + b[i][j];
}
}
System.out.println("The sum of the two matrices =");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
System.out.print(c[i][j] + " ");
}
System.out.println();
}
}
}
Output:
Enter number of rows: 2
Enter number of columns: 2
Enter the first matrix
1 2
3 4
Enter the second matrix
1 4
3 5
The sum of the two matrices =
2 6
6 9
0 comments:
Post a Comment