Java Program to Add Two Matrices

Java program to add two matrices. “A matrix is a set of integers organized into a predetermined number of rows and columns.” These are usually real numbers. A two-dimensional array has two dimensions, one for each row and one for each column.

import java.util.Scanner;
class Main
{
public static void main(String args[])
{
int m, n, c, d;
Scanner in = new Scanner(System.in);
System.out.println("Enter the rows and columns");
m = in.nextInt();
n = in.nextInt();
int first[][] = new int[m][n];
int second[][] = new int[m][n];
int sum[][] = new int[m][n];
System.out.println("Enter the elements of first matrix");
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
first[c][d] = in.nextInt();
System.out.println("Enter the elements of second matrix");
for (c = 0 ; c < m; c++)
for (d = 0 ; d < n; d++)
second[c][d] = in.nextInt();
for (c = 0; c < m; c++)
for (d = 0; d < n; d++)
sum[c][d] = first[c][d] + second[c][d];
System.out.println("Sum of the matrices:");
for (c = 0; c < m; c++)
{
for (d = 0; d < n; d++)
System.out.print(sum[c][d] + "\t");
System.out.println();
}
}
}

 

Output:

Enter the rows and columns
2
2
Enter the elements of first matrix
34
56
67
89
Enter the elements of second matrix
67
789
4
34
Sum of the matrices:
101 845
71 123

Add Two Matrices and How to Execute This Program

A matrix is a rectangular array of numbers that are arranged in rows and columns. The numbers are referred to as the matrix’s elements or entries. Engineering, physics, economics, and statistics, as well as various disciplines of mathematics, all use matrices. In this example, we have a 3 2 matrix, which means that the number of rows equals 3 and the number of columns equals 2.

Uses of Matrices

They are used to create graphs, calculate statistics, and conduct scientific studies and research in a variety of subjects. Matrices can also be used to represent real-world information such as population, infant mortality rate, and so on. 

For charting surveys, these are the finest representation methods. Addition of Two Matrix in Java this will addition of two matrices program.

How Does the Matrix Works in Java

We use the term rows and columns to show how many rows and columns a matrix has. When multiplying two matrices, the first matrix’s column count must equal the second matrix’s row count. The result will have the same number of rows and columns as the first matrix. Addition of Two Matrix in Java for developer in software programming.

Addition of Two Matrix in Java Program

A matrix can only be added to another matrix if the dimensions of the two matrices are the same. Simply add the corresponding entries from two matrices and place the sum in the corresponding position in the resulting matrix. Java Program to Add Two Matrices Using this program we can addition of two matrix for beginners.

Compiler: Click Here