Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /* Java programme to multiply mattrix*/
- package Matrix;
- import java.util.Scanner;
- public class Matrix1
- {
- public static void main(String[] args)
- {
- int r1, c1, r2, c2, i=0, j=0, k;
- int[][] a=new int[10][10];
- int[][] b=new int[10][10];
- Scanner myobject = new Scanner(System.in);
- System.out.println("Enter rows and column for first matrix: ");
- r1=myobject.nextInt();
- c1=myobject.nextInt();
- System.out.println("Enter rows and column for second matrix: ");
- r2=myobject.nextInt();
- c2=myobject.nextInt();
- int[][] mult=new int[r1][c2];
- /* If colum of first matrix in not equal to row of second matrix, asking user to enter the size of matrix again. */
- while (c1!=r2)
- {
- System.out.println("Error! column of first matrix not equal to row of second.\n\n");
- System.out.println("Enter rows and column for first matrix: ");
- r1=myobject.nextInt();
- c1=myobject.nextInt();
- System.out.println("Enter rows and column for second matrix: ");
- r2=myobject.nextInt();
- c2=myobject.nextInt();
- }
- /* Storing elements of first matrix. */
- System.out.println("Enter elements of matrix 1:");
- for(i=0; i<r1; ++i)
- {
- for(j=0; j<c1; ++j)
- {
- System.out.println("Enter elements"+" a["+(i+1)+"]["+(j+1)+"]: ");
- a[i][j]=myobject.nextInt();
- }
- }
- /* Storing elements of second matrix. */
- System.out.println("\nEnter elements of matrix 2 : ");
- for(i=0; i<r2; ++i)
- {
- for(j=0; j<c2; ++j)
- {
- System.out.println("Enter elements"+" b["+(i+1)+"]["+(j+1)+"]: ");
- b[i][j]=myobject.nextInt();
- }
- }
- /*Initializing elements of matrix mult to 0.*/
- for(i=0; i<r1; ++i)
- {
- for(j=0; j<c2; ++j)
- {
- mult[i][j]=0;
- }
- }
- /* Multiplying matrix a and b and storing in array mult. */
- for(i=0; i<r1; ++i)
- {
- for(j=0; j<c2; ++j)
- {
- for(k=0; k<c1; ++k)
- {
- mult[i][j]+=a[i][k]*b[k][j];
- }
- }
- }
- /* Displaying the multiplication of two matrix. */
- System.out.println("\nOutput Matrix:\n");
- for(i=0; i<r1; ++i)
- {
- for(j=0; j<c2; ++j)
- {
- System.out.println(" "+mult[i][j]);
- if(j==c2-1)
- {
- System.out.println("\n\n");
- }
- }
- }
- }
- }
Add Comment
Please, Sign In to add comment