To multiply 2D array in java
CODE :
public class P_02_2dArrayMultiplication{
public static void main(String[] args) {
int n = 2;
int[][] a = {{1,2},{4,5}};
int[][] b = {{2,1},{5,6}};
int[][] c = new int[n][n];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
for (int k = 0; k < n; k++)
{
c[i][j] = c[i][j] + a[i][k] * b[k][j];
}
}
}
System.out.println("The product is:");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
System.out.print(c[i][j] + " ");
}
System.out.println();
}
}
}
Output :
public class P_02_2dArrayMultiplication{
public static void main(String[] args) {
int n = 2;
int[][] a = {{1,2},{4,5}};
int[][] b = {{2,1},{5,6}};
int[][] c = new int[n][n];
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
for (int k = 0; k < n; k++)
{
c[i][j] = c[i][j] + a[i][k] * b[k][j];
}
}
}
System.out.println("The product is:");
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
System.out.print(c[i][j] + " ");
}
System.out.println();
}
}
}
Output :
Comments
Post a Comment