Matrix Addition using simplest way...........
Write a java program to add two matrices :
import java.util.Scanner;
public class AddTwoMatrix {
public static void main(String[] args) {
System.out.println("Enter Read first matrix : ");
int[][] a=readmatrix();
System.out.println("Enter second matrix : ");
int b[][]=readmatrix();
int res[][]=addMat(a, b);
System.out.println("First matrix is : ");
dispMat(a);
System.out.println("Second matrix is : ");
dispMat(b);
System.out.println("Result matrix is : ");
dispMat(res);
}
static int[][] readmatrix(){
Scanner sc=new Scanner(System.in);
System.out.println("Enter Row size and column size :");
int row=sc.nextInt();
int col=sc.nextInt();
int mat[][]=new int[row][col];
System.out.println("Enter Elements in Table : ");
for(int i=0;i<row;i++) {
for(int j=0;j<col;j++) {
mat[i][j]=sc.nextInt();
}
}return mat;
}
static int[][] addMat(int x[][],int y[][]){
if((x.length!=y.length) || (x[0].length!=y[0].length)) {
System.out.println("Addition is not possible :");
return null;
}
int[][] res=new int[x.length][x[0].length];
for(int i=0;i<res.length;i++) {
for(int j=0;j<res[i].length;j++) {
res[i][j]=x[i][j]+y[i][j];
}
} return res;
}
static void dispMat(int mat[][]) {
for(int i=0;i<mat.length;i++) {
for(int j=0;j<mat[i].length;j++) {
System.out.print(mat[i][j]+" ");
}System.out.println();
}
}
}
Comments
Post a Comment