Saturday, January 31, 2015

Java program to multiply two matrices after getting input

The program given below is able to multiply two matrices. After running the program, you will be asked to provide the number of rows of the first matrix and then you will be asked to provide the number of columns.

In the next step you will be asked to provide the data/element of the first matrix and soon the matrix will be displayed. Besides, you will be asked to provide the number of columns for the second matrix.
import java.util.Scanner;

class MatrixMultiplication{
	public static void main(String args[]){
		//declaring integer type data
		int i, j, k, sum=0;

		//creating scaner object
		Scanner in = new Scanner(System.in);

		//getting the number of rows and columns
		System.out.print("Enter the number of rows of first matrix: ");
		int rows1 = in.nextInt();
		System.out.print("Enter the number of columns of first matrix: ");
		int col1 = in.nextInt();

		int first[][] = new int[rows1][col1];

		//getting input for the first matrix
		System.out.println("\n\nEnter the data of first matrix:");
		for(i=0; i<rows1; i++){
			for(j=0; j<col1; j++){
				first[i][j]= in.nextInt();
			}
		}

		//Displaying first matrix
		System.out.println("\n\nThe first matrix is:");
		for(i=0; i<rows1; i++){
			for(j=0; j<col1; j++){
				System.out.print(first[i][j]+"\t");
			}System.out.print("\n\n\n");
		}

		//getting the number of rows and columns of the second matrix
		System.out.print("\n\nEnter the number of rows of second matrix: ");
		int rows2 = in.nextInt();
		System.out.print("Enter the number of columns of second matrix: ");
		int col2 = in.nextInt();

		//checking if the operation is possible or not
		if (col1 != rows2){
			System.out.println("\n\nThe operation is impossible!");
			System.out.println("As the number od rows and columns are not same.");
		} else {
			int second[][] = new int[rows2][col2];
			int multiply[][] = new int[rows1][col2];

		//getting input for the second matrix
		System.out.println("\n\nEnter the data of second matrix");
		for (i=0; i<rows2; i++){
			for (j=0; j<col2; j++){
				second[i][j] = in.nextInt();
			}
		}


		//displaying the second matrix
		System.out.println("\n\nThe second matrix is:");
		for(i=0; i<rows2; i++){
			for(j=0; j<col2; j++){
				System.out.print(second[i][j]+"\t");
			}System.out.print("\n\n\n");
		}

		//multiplying two matrices
		for (i=0; i<rows1; i++){
			for (j=0; j<col2; j++){
				for (k=0; k<rows2; k++){
					sum=sum+first[i][k]*second[k][j];
					}
               multiply[i][j] = sum;
               sum = 0;
               }
        }

		//displaying the product
		System.out.println("\n\nProduct of entered matrices:");
		for (i=0; i<rows1; i++){
			for (j=0; j<col2; j++){
				System.out.print(multiply[i][j]+"\t");
				}
				System.out.print("\n\n\n\n");
			}
		}
   }
}


No comments:

Post a Comment