Multiplication of Two Matrices

This program multiplies two matrices.

Problem Statement

Write a Java program to multiply two 3x3 matrices.

Source Code

1 public class MatrixMultiplication {
2 public static void main(String[] args) {
3 int[][] A = {{1,2,3},{4,5,6},{7,8,9}};
4 int[][] B = {{9,8,7},{6,5,4},{3,2,1}};
5 int[][] C = new int[3][3];
6 for(int i=0;i<3;i++){
7 for(int j=0;j<3;j++){
8 C[i][j]=0;
9 for(int k=0;k<3;k++){
10 C[i][j]+=A[i][k]*B[k][j];
11 }
12 }
13 }
14 for(int i=0;i<3;i++){
15 for(int j=0;j<3;j++){
16 System.out.print(C[i][j]+" ");
17 }
18 System.out.println();
19 }
20 }
21 }

Program Output

30 24 18 
84 69 54 
138 114 90 

Explanation

Matrix multiplication requires three nested loops: the outer two iterate rows and columns of the result, while the innermost loop computes the dot product of the corresponding row and column, demonstrating a more complex multidimensional array operation.

Quick Links to Explore