Matrix Multiplication Java

PROGRAM TO MULTIPLY TWO MATRICES


import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    //M = rows, N = columns
    int M = sc.nextInt();
    int N = sc.nextInt();
    int[][] matA = new int[M][N];
    int[][] matB = new int[M][N];
    for(int i=0; i<M; i++)
      for(int j=0; j<N; j++)
        matA[i][j] = sc.nextInt();
    for(int i=0; i<M; i++)
      for(int j=0; j<N; j++)
        matB[i][j] = sc.nextInt();
    
    int[][] product = new int[M][N];
    for(int i=0; i<M; i++) {
      for(int j=0; j<N; j++) {
        for(int k=0; k<N; k++) {
          product[i][j] += matA[i][k] * matB[k][j];
        }
      }
    }

    for(int i=0; i<M; i++) {
      for(int j=0; j<N; j++)
        System.out.print(product[i][j] + " ");
      System.out.println();
    }
  }
}


OUTPUT:





Comments

Popular posts from this blog

Solve the Sudoku Python

Solve the Sudoku Java

Find Duplicates Java