Click here to Skip to main content
15,916,949 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
write a java program to find a product of 2d matrix using any one concept of inheritance

What I have tried:

public class ProdMatrix
{
public static void main(String[] args) {
int row1, col1, row2, col2;
//Initialize matrix a
int a[][] = {
{1, 3, 2},
{3, 1, 1},
{1, 2, 2}
};

//Initialize matrix b
int b[][] = {
{2, 1, 1},
{1, 0, 1},
{1, 3, 1}
};

//Calculates number of rows and columns present in first matrix
row1 = a.length;
col1 = a[0].length;

//Calculates the number of rows and columns present in the second matrix

row2 = b.length;
col2 = b[0].length;

//For two matrices to be multiplied,
//number of columns in first matrix must be equal to number of rows in second matrix
if(col1 != row2){
System.out.println("Matrices cannot be multiplied");
}
else{
//Array prod will hold the result
int prod[][] = new int[row1][col2];

//Performs product of matrices a and b. Store the result in matrix prod
for(int i = 0; i < row1; i++){
for(int j = 0; j < col2; j++){
for(int k = 0; k < row2; k++){
prod[i][j] = prod[i][j] + a[i][k] * b[k][j];
}
}
}

System.out.println("Product of two matrices: ");
for(int i = 0; i < row1; i++){
for(int j = 0; j < col2; j++){
System.out.print(prod[i][j] + " ");
}
System.out.println();
}
}
}}
Posted
Updated 30-Mar-23 7:59am
Comments
Dave Kreskowiak 30-Mar-23 13:51pm    
Did you have a question or problem that you forgot to explain?

1 solution

Read the question. It is very specific about one element you must implement:
Quote:
using any one concept of inheritance

Without implementing at least two classes, you cannot demonstrate inheritance at all - so finding code on the internet and hoping that'll do isn't going to work ...
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900