Home »
Java Programs »
Core Java Example Programs
Java program to add two matrices
Program to add two matrices in Java
This program will read two matrices and print other matrix having addition of first and second matrices. Third matrix will be addition matrix of inputted two matrices.
Adding Two Matrices using Java program
//Java program to add two matrices.
import java.util.*;
public class AddMatrices
{
public static void main(String args[])
{
int row,col;
Scanner sc=new Scanner(System.in);
//Read number of rows and cols
System.out.print("Input number of rows: ");
row=sc.nextInt();
System.out.print("Input number of rows: ");
col=sc.nextInt();
//declare two dimensional array (matrices)
int a[][]=new int[row][col]; //for matrix 1
int b[][]=new int[row][col]; //for matrix 2
int c[][]=new int[row][col]; //for matrix 3
//Read elements of Matrix a
System.out.println("Enter elements of matrix a:");
for(int i=0; i<row; i++)
{
for(int j=0; j<col; j++)
{
System.out.print("Element [" + (i+1) + "," + (j+1) + "] ? ");
a[i][j]=sc.nextInt();
}
}
//Read elements of Matrix b
System.out.println("Enter elements of matrix b:");
for(int i=0; i<row; i++)
{
for(int j=0; j<col; j++)
{
System.out.print("Element [" + (i+1) + "," + (j+1) + "] ? ");
b[i][j]=sc.nextInt();
}
}
//print matrix a
System.out.println("Matrix a:");
for(int i=0; i<row; i++){
for(int j=0; j<col; j++){
System.out.print(a[i][j] + "\t");
}
System.out.print("\n");
}
//print matrix b
System.out.println("Matrix b:");
for(int i=0; i<row; i++){
for(int j=0; j<col; j++){
System.out.print(b[i][j] + "\t");
}
System.out.print("\n");
}
//adding matrices
for(int i=0; i<row; i++){
for(int j=0; j<col; j++){
c[i][j]=a[i][j];
}
}
//print matrix b
System.out.println(":: Final Matrix:");
for(int i=0; i<row; i++){
for(int j=0; j<col; j++){
System.out.print(c[i][j] + "\t");
}
System.out.print("\n");
}
}
}
Output
me@linux:~$ javac AddMatrices.java
me@linux:~$ java AddMatrices
Input number of rows: 2
Input number of rows: 3
Enter elements of matrix a:
Element [1,1] ? 1
Element [1,2] ? 2
Element [1,3] ? 3
Element [2,1] ? 4
Element [2,2] ? 5
Element [2,3] ? 6
Enter elements of matrix b:
Element [1,1] ? 7
Element [1,2] ? 6
Element [1,3] ? 5
Element [2,1] ? 7
Element [2,2] ? 8
Element [2,3] ? 5
Matrix a:
1 2 3
4 5 6
Matrix b:
7 6 5
7 8 5
:: Final Matrix:
1 2 3
4 5 6
Core Java Example Programs »