Write a Program in MatrixMultiplication using Java - Technology369kk

 Program


import java.util.Scanner;

class MatrixMultiplication {
public static void main(String[] args) {
int num;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the size of square matrices: ");
num = sc.nextInt();

int[][] a = new int[num][num];
int[][] b = new int[num][num];
int[][] c = new int[num][num];

System.out.println("Enter the elements of the 1st Matrix row-wise: ");
for (int i = 0; i < num; i++) {
for (int j = 0; j < num; j++) {
a[i][j] = sc.nextInt();
}
}

System.out.println("Enter the elements of the 2nd Matrix row-wise: ");
for (int i = 0; i < num; i++) {
for (int j = 0; j < num; j++) {
b[i][j] = sc.nextInt();
}
}

// Initialize the result matrix to zero
for (int i = 0; i < num; i++) {
for (int j = 0; j < num; j++) {
c[i][j] = 0;
}
}

System.out.println("Multiplying the matrices: ");
for (int i = 0; i < num; i++) {
for (int j = 0; j < num; j++) {
for (int k = 0; k < num; k++) {
c[i][j] += a[i][k] * b[k][j];
}
}
}

System.out.println("The Product is: ");
for (int i = 0; i < num; i++) {
for (int j = 0; j < num; j++) {
System.out.print(c[i][j] + " ");
}
System.out.println();
}
}
}


Answer: 



Enter the size of square matrices:
2
Enter the elements of the 1st Matrix row-wise:
4
5
6
6
Enter the elements of the 2nd Matrix row-wise:
3
5
8
9
Multiplying the matrices:
The Product is:
52 65
66 84 
 


Post a Comment

0 Comments