Java matrix addition
In this program, we are performing the addition of two matrices. Here we define two matrix one is first[][]
and another is second[][] and another one defines for summation of two entered matrices. First, we take row and column and then enter the values in two matrices. After then we sum the two matrices.
import java.util.Scanner;
/**
* Java program for
* Addition Of Two Matrices
*/
public class AdditionOfTwoMatrices
{
public static void main(String args[])
{
int m, n, i, j; // Local Variables
Scanner sc = new Scanner(System.in);
System.out.println("Enter the number of rows and columns of matrix");
m = sc.nextInt();
n = sc.nextInt();
// Array definition
int first[][] = new int[m][n]; // First Array
int second[][] = new int[m][n]; // Second Array
int add[][] = new int[m][n]; // sum of two matrix array
System.out.println("Enter the elements of first matrix");
for ( i = 0 ; i < m ; i++ )
{
for ( j = 0 ; j < n ; j++ )
{
first[i][j] = sc.nextInt();
}
}
System.out.println("Enter the elements of second matrix");
for ( i = 0 ; i < m ; i++ )
{
for ( j = 0 ; j < n ; j++ )
{
second[i][j] = sc.nextInt();
}
}
// Display of First Matrix
System.out.println("Output of First Matrix");
for ( i = 0 ; i < m ; i++ )
{
for ( j = 0 ; j < n ; j++ )
{
System.out.print(first[i][j] + " ");
}
System.out.println();
}
// Display of Second Matrix
System.out.println("Output of Second Matrix");
for ( i = 0 ; i < m ; i++ )
{
for ( j = 0 ; j < n ; j++ )
{
System.out.print(second[i][j] + " ");
}
System.out.println();
}
// Addition of matrix
for ( i = 0 ; i < m ; i++ )
{
for ( j = 0 ; j < n ; j++ )
{
add[i][j] = first[i][j] + second[i][j];
}
}
// Display of Matrix addition
System.out.println("Addition of Two Matrix");
for ( i = 0 ; i < m ; i++ )
{
for ( j = 0 ; j < n ; j++ )
{
System.out.print(add[i][j]+"\t");
}
System.out.println();
}
}
}
Output
Enter the number of rows and columns of matrix
2
2
Enter the elements of first matrix
7
8
9
4
Enter the elements of second matrix
5
6
1
2
Output of First Matrix
7 8
9 4
Output of Second Matrix
5 6
1 2
Addition of Two Matrix
12 14
10 6