Java Program To Add Two Matrices Example
Chapter:
Miscellaneous
Last Updated:
25-06-2016 20:54:47 UTC
Program:
/* ............... START ............... */
import java.util.Scanner;
public class JavaAddTwoMatricesExample {
public static void main(String args[])
{
int rows, cols, c, d;
Scanner scanner = new Scanner(System.in);
System.out.println("Please Enter number of rows and columns");
rows = scanner.nextInt();
cols = scanner.nextInt();
int first[][] = new int[rows][cols];
int second[][] = new int[rows][cols];
int sum[][] = new int[rows][cols];
System.out.println("Please Enter elements of first matrix");
for ( c = 0 ; c < rows ; c++ )
for ( d = 0 ; d < cols ; d++ )
first[c][d] = scanner.nextInt();
System.out.println("Please Enter elements of second matrix");
for ( c = 0 ; c < rows ; c++ )
for ( d = 0 ; d < cols ; d++ )
second[c][d] = scanner.nextInt();
for ( c = 0 ; c < rows ; c++ )
for ( d = 0 ; d < cols ; d++ )
sum[c][d] = first[c][d] + second[c][d];
System.out.println("Sum of entered matrices:-");
for ( c = 0 ; c < rows ; c++ )
{
for ( d = 0 ; d < cols ; d++ )
System.out.print(sum[c][d]+"\t");
System.out.println();
}
}
}
/* ............... END ............... */
Output
Please Enter number of rows and columns
2
3
Please Enter elements of first matrix
2
2
4
5
5
6
Please Enter elements of second matrix
3
4
6
4
6
4
Sum of entered matrices:-
5 6 10
9 11 10
Tags
Add Two Matrices Example, Java