Java Matrix Addition
Chapter:
Math Class
Last Updated:
17-05-2017 16:35:29 UTC
Program:
/* ............... START ............... */
import java.util.Scanner;
public class JavaMatrixAddition {
public static void main(String args[]) {
int rows, columns, c, d;
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of rows and columns of matrix");
rows = in.nextInt();
columns = in.nextInt();
int matrix1[][] = new int[rows][columns];
int matrix2[][] = new int[rows][columns];
int sum[][] = new int[rows][columns];
System.out.println("Enter the elements of matrix1");
for (c = 0; c < rows; c++) {
for (d = 0; d < columns; d++) {
matrix1[c][d] = in.nextInt();
}
}
System.out.println("Enter the elements of matrix2");
for (c = 0; c < rows; c++) {
for (d = 0; d < columns; d++) {
matrix2[c][d] = in.nextInt();
}
}
for (c = 0; c < rows; c++) {
for (d = 0; d < columns; d++) {
sum[c][d] = matrix1[c][d] + matrix2[c][d];
}
}
System.out.println("Sum of entered matrices:");
for (c = 0; c < rows; c++) {
for (d = 0; d < columns; d++) {
System.out.print(sum[c][d] + "\t");
}
System.out.println();
}
}
}
/* ............... END ............... */
Output
Enter the number of rows and columns of matrix
2
2
Enter the elements of matrix1
3
4
5
6
Enter the elements of matrix2
2
2
5
6
Sum of entered matrices:
5 6
10 12
Notes:
-
Matrix addition is the operation of adding two matrices by adding the corresponding entries together. Two matrices must have an equal number of rows and columns to be added.
Tags
Matrix Addition, Java, Math