The program for addition of two matrices uses simple arithmetic operations on two given matrices and prints the output.

It is written in NetBeans 8.2 installed on a windows 7 64-bit system. You may also need to install the Java SDK version suitable for NetBeans 8.2.

It is a simple demonstration of arithmetic operations and it is intended for beginner level learner of Java programming.

Problem Definition

We reads two matrices – matrix A and matrix B and adds each corresponding element of the given matrix. The result of this addition is stored in a third matrix C.

For example, let A, B, and C be 3 x 3 matrices. Then

Matrix Addition
Matrix Addition

In the above figure, each element from first row of A is added to each element of the B and the sum is stored in the matrix C.

Flowchart

Flowchart - Matrix Addition
Flowchart – Matrix Addition

Program Code

/* To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */	


/**
*
* @author Admin
*/
public class Matrixaddition {

    int a[][] = {{1,2,3},{2,3,5},{4,2,1}};

    int b[][] = {{3,2,2},{0,1,1},{1,1,7}};

    int c[][] = new int [3][3];

    void addmatrix(){

        int i,j;
        for(i=0;i< 3;i++){

            for(j=0;j < 3;j++){

                c[i][j] = a[i][j] + b[i][j];
                }
        }
    }

void display(){

    int i,j;

    for(i=0;i < 3;i++){

        for(j=0;j < 3;j++){

            System.out.print (c[i][j] + " ");

            }
        System.out.println("\n");
        }
    }

public static void main(String[] args)
{
    Matrixaddition obj = new Matrixaddition();

    obj.addmatrix();
    obj.display();
}
}

Output

4      4      5

2      4      6

5      3      8