Friday, July 30, 2010

Java Program for Matrix Multiplication

Here goes the Java Program to multiply Two matrices, written by me....Requires Scanner package to run this( available with new versions of Java JDK).

(Pls download the source code in case if it is not clear below)

import java.util.Scanner;
public class matrix_main
{
public static void main(String[] args)
{
Scanner cin=new Scanner(System.in);
int A_row,A_col,B_row,B_col;
System.out.println("Enter the number of rows in matrix A : ");
A_row=cin.nextInt();
System.out.println("Enter the number of columns in matrix A : ");
A_col=cin.nextInt();
System.out.println("Enter the number of rows in matrix B : ");
B_row= cin.nextInt();
System.out.println("Enter the number of columns in matrix B : ");
B_col=cin.nextInt();

if(A_col==B_row)
{
int matrix_A[][] =new int[A_row][A_col];
int matrix_B[][] =new int[B_row][B_col];
int mult_ans[][] =new int[A_row][B_col];
System.out.println("Enter the elements of matrix A : ");
for(int i=0;i for(int j=0;j {
matrix_A[i][j]=cin.nextInt();
}
System.out.println("Enter the elements of matrix B : ");
for(int i=0;i for(int j=0;j {
matrix_B[i][j]=cin.nextInt();
}
for(int i=0;i for(int j=0;j for(int k=0;k mult_ans[i][j] += matrix_A[i][k] * matrix_B[k][j];

System.out.println("\n\n The output is:");
for(int i=0;i {
for(int j=0;j {
System.out.print(mult_ans[i][j]+" ");
}
System.out.println();
}

}
else
{

System.out.print("!!! Can't multiply this matrixes !!! ");
}
}

}



Download The Source Code

No comments: