Program in Java for Addition of Two Matrices

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

Advertisements

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.

Advertisements

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.
 */	

package JavaExamples;

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

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

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

    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

Related Articles:-

Advertisements

Ads Blocker Image Powered by Code Help Pro

Ads Blocker Detected!!!

We have detected that you are using extensions to block ads. Please support us by disabling these ads blocker.