Matrix Multiplication Using Arrays And Loops in Java

 

Do Matrix Multiplication in Java by the help of Arrays and Loops

Answer:

I used Vs Code as IDE, you can also use Eclipse and run the code in your computer. The result Image shown at the bottom. I used 2x2 matrix, you can also use for big matrixes, and remember that first matrix column must be equal with the rows of second matrix.

import java.util.Scanner;
public class Ques4 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Please Enter Dimension");
        System.out.println("In Matrix multiplication rows and columns must be same!");
        int rows = sc.nextInt();
        int cols = sc.nextInt();

        int a[][] = new int[rows][cols];
        int b[][] = new int[rows][cols];

        System.out.println("Enter array A");
        for(int i = 0irowsi++){
            for(int j = 0jcolsj++){
                a[i][j] = sc.nextInt();
            }
        }
        System.out.println("Enter array B");
        for(int i = 0irowsi++){
            for(int j = 0jcolsj++){
                b[i][j] = sc.nextInt();
            }
        }
        int c[][] = new int[rows][cols];
        for(int i = 0i<rowsi++){
            for(int j = 0j<colsj++){
                c[i][j] = a[i][j] * b[j][i] +  a[i][j] * b[j][i];
            }
        }
        System.out.println("Matrix multiplication result C is");

        System.out.println("Result array C");
        for(int i = 0irowsi++){
            for(int j = 0jcolsj++){
                System.out.print(c[i][j] + " ");
            }
            System.out.println();
        }
        sc.close();
    }
    
}





Comments

Popular posts from this blog

Simple Rock Paper Scissors Game(Java)

Access denied in VS code for gcc while doing C programming

HackerRank 30 Days Of Code Challenge, Day8(Ques 9 in Java)