Java Programs

Please click on 1-2 Ads to keep this website's Study Material FREE and regularly Updated.

Program 32: Write a Java program to calculate the multiplication of two matrices.

Multiplication.java

import java.util.Scanner;

public class Multiplication
{
	public static void main(String[] args)
	{
		Scanner s = new Scanner(System.in);
			
		//Input Size in matrix-1.
		System.out.println("Enter the size of the matrix1");
		int row1=s.nextInt();
		int col1=s.nextInt();

		//Input Elements in matrix-1.
		int a[][] = new int[row1][col1];

		System.out.println("Enter elements of first matrix");
		for(int i=0; i < row1; i++)
		{
			for(int j=0; j < col1;j++)
			{
				System.out.print("Enter "+i+j+" element: ");
				a[i][j]=s.nextInt();	
			}
		}
		
		//Input Size in matrix-2.
		System.out.println("Enter the size of the matrix2");
		int row2=s.nextInt();
		int col2=s.nextInt();

		//Input Elements in matrix-2.
		int b[][] = new int[row2][col2];
		System.out.println("Enter elements of second matrix");

		for(int i=0; i < row2; i++)
		{
			for(int j=0; j < col2;j++)
			{
				System.out.print("Enter "+i+j+" element: ");
				b[i][j]=s.nextInt();	
			}
		}
		
		if(col1!=row2)
		{
			System.out.println("Matrices cannot be multipled");
		
		}
		else
		{
			int prod[][] = new int[row1][col2];
		
			//Performs product of two matrices a and b then store the result in matrix prod.
			for(int i=0; i < row1;i++)
			{
				for(int j=0; j < col2;j++)
				{
					for(int k=0; k < row2;k++)
					{
						prod[i][j]=prod[i][j]+a[i][k]*b[k][j];
					}
				}
			}
		
			//Displaying the resultant matrix.
			System.out.println("Product of two matrices");
			for(int i=0; i < row1; i++)
			{
				for(int j=0; j < col2;j++)
				{
					System.out.print(prod[i][j]+" ");
				}
				System.out.println();
			}
		}
	}
}



If you have any suggestion or found any error in the above program, then do let us know at [email protected] or just comment below.