Java Program for Matrix Addition

Here you will get java program for matrix addition.

If you have ever done addition of two matrices in your maths subject then you can easily do this in java also. It can be done in following way.

  1. Read two matrices in 2D array a[][] and b[][] respectively inside loop.
  2. Now add each element of a[][] with corresponding position element of b[][] and save the result in c[][].
  3. Finally display the 2D array c[][].

Note: The addition is possible only when the dimensions of two matrices are equal.

Java Program for Matrix Addition

import java.util.Scanner;

public class JavaMatrixAddition {
	public static void main(String args[]){
		int i,j,m,n;
		Scanner sc = new Scanner(System.in);
		
		System.out.println("Enter number of rows and columns:");
		m = sc.nextInt();
		n = sc.nextInt();
		
		int a[][] = new int[m][n];
		int b[][] = new int[m][n];
		int c[][] = new int[m][n];
		
		//reading first matrix
		System.out.println("\nEnter elements of first matrix row wsie:");
		for(i = 0; i < m; ++i){
			for(j = 0; j < n; ++j){
				a[i][j] = sc.nextInt();
			}
		}
		
		//reading second matrix
		System.out.println("\nEnter elements of second matrix row wsie:");
		for(i = 0; i < m; ++i){
			for(j = 0; j < n; ++j){
				b[i][j] = sc.nextInt();
			}
		}

		//performing addition of two matrices
		for(i = 0; i < m; ++i){
			for(j = 0; j < n; ++j){
				c[i][j] = a[i][j] + b[i][j];
			}
		}
		
		//printing the resultant matrix
		System.out.println("\nAddtion of two matrices is:");
		for(i = 0; i < m; ++i){
			for(j = 0; j < n; ++j){
				System.out.print(c[i][j] + " ");
			}
			
			System.out.print("\n");
		}
	}
}

Output

Enter number of rows and columns:
2
2

Enter elements of first matrix row wsie:
2 6
7 9

Enter elements of second matrix row wsie:
12 3
0 4

Addtion of two matrices is:
14 9
7 13

Leave a Comment

Your email address will not be published. Required fields are marked *