Friday, 24 April 2015

Filled Under:

How To Perform Matrix Addition Using 2D Array In Java

Often we require to perform matrix addition in our program here is the example of mattix addition using 2d array 

CODING:

import java.util.Scanner;
class MatrixAddition {

Scanner scan;
int matrix1[][], matrix2[][], sum[][];
int row, column;

void create() {

scan = new Scanner(System.in);

//Creation of first Matrix..
System.out.println("\nEnter number of rows ");
row = Integer.parseInt(scan.nextLine());
System.out.println("\nEnter number of columns ");
column = Integer.parseInt(scan.nextLine());

matrix1 = new int[row][column];
matrix2 = new int[row][column];
sum = new int[row][column];

System.out.println("Enter the data for first matrix :");

for(int i=0; i < row; i++) {

for(int j=0; j < column; j++) {

matrix1[i][j] = scan.nextInt();
}
}

//Creation of second matrix..
System.out.println("Enter the data for second matrix :");

for(int i=0; i < row; i++) {

for(int j=0; j < column; j++) {

matrix2[i][j] = scan.nextInt();
}
}
}

void display() {

System.out.println("The First Matrix is :");

for(int i=0; i < row; i++) {

for(int j=0; j < column; j++) {

System.out.print("\t" + matrix1[i][j]);
}
System.out.println();
}

System.out.println("\nThe Second Matrix is :");

for(int i=0; i < row; i++) {

for(int j=0; j < column; j++) {

System.out.print("\t" + matrix2[i][j]);
}
System.out.println();
}
}

void add() {

for(int i=0; i < row; i++) {

for(int j=0; j < column; j++) {

sum[i][j] = matrix1[i][j] + matrix2[i][j];
}
}

System.out.println("\n\nThe Sum is :");

for(int i=0; i < row; i++) {

for(int j=0; j < column; j++) {

System.out.print("\t" + sum[i][j]);
}
System.out.println();
}
}
}

class MatrixAdditionExample 
{

public static void main(String args[])
{

MatrixAddition x = new MatrixAddition();

x.create();
x.display();
x.add();
}
}

OUTPUT:



0 comments:

Post a Comment