In this section we will learn about addition of two matrices. In java this is a simple program to adding two matrices, we have to take two-dimensional array and the result should be saved in third two-dimensional array. Here we are going to develop a Java code for matrices addition, while adding two matrices the number of row and column of first matrix is equal to number of rows and column of second matrix, and both array will initialize with the number of rows and column provided by user. Two for loop is used, one which executes up to the number of rows and second for loop will execute up to the number of column. After getting the number of rows, number of columns and element of both arrays, add both and store it in resultant array that is c.

import java.util.Scanner; class MatrixAddition { public static void main(String args[]) { int m, n, i, j; Scanner in = new Scanner(System.in); System.out.println(""); System.out.println("Enter the number of rows and columns of first matrix"); m = in.nextInt(); n = in.nextInt(); int a[][] = new int[m][n]; int b[][] = new int[m][m]; int c[][] = new int[m][n]; System.out.println("Enter the elements of first matrix"); for ( i = 0 ; i < m ; i++ ) for ( j = 0 ; j < n ; j++ ) a[i][j] = in.nextInt(); System.out.println("Enter the number of rows and columns of second matrix"); m = in.nextInt(); n = in.nextInt(); System.out.println("Enter the elements of second matrix"); for ( i = 0 ; i < m ; i++ ) { for ( j = 0 ; j < n ; j++ ) { b[i][j] = in.nextInt(); } } for ( i = 0 ; i < m ; i++ ) { for ( j = 0 ; j < n ; j++ ) { c[i][j]= a[i][j]+b[i][j]; //Adding two matrices } } System.out.println("After addition of the two matrices:-"); for ( i = 0 ; i < m ; i++ ) { for ( j = 0 ; j < n ; j++ ) System.out.print(c[i][j]+"\t"); System.out.print("\n"); } } }

**Output : **After compiling and executing above program

Advertisements

Posted on: June 11, 2013 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms. Connect Me on Google+

Comments:0

Discuss: Matrix addition in javaPost your Comment