Java program which will add the values of 2d matrix horizontally with another 2d matrix vertically
import java.util.*;
class MatrixAddition{
public static void main(String args[]){
int matrix1[][]=new int[2][2];
int matrix2[][]=new int[2][2];
int res_matrix[][]=new int[2][2];
int i, j;
Scanner sc=new Scanner(System.in);
// reading the elements of first matrix
System.out.println(" enter elements of first matrix ");
for( i=0; i<2 ;i++){
for(j=0;j<2;j++){
matrix1[i][j]=sc.nextInt();
}
}
// reading the elements of second matrix
System.out.println(" enter the elements of second matrix ");
for( i=0; i<2; i++){
for(j=0; j<2; j++){
matrix2[i][j]=sc.nextInt();
}
}
// adding two matrices`
for( i=0; i<2; i++){
for (j=0; j<2; j++){
res_matrix[i][j]= matrix1[i][j] + matrix2[j][i];
}
}
// printing the resultant matrix
System.out.println(" the resultant matrix is \n");
for (i=0; i<2; i++){
for( j=0; j<2; j++){
System.out.print(res_matrix[i][j]+" ");
}
System.out.println("");
}
}
}
No comments:
Post a Comment