Java Program to multiply two matrices

Friday, October 2nd, 2009
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import java.util.Scanner;
class matmul
{
	public static void main(String args[])
	{
		int a[][]=new int[3][3];
		int b[][]=new int[3][3];
		int c[][]=new int[3][3];
		System.out.println("Enter the first matrix:");
		Scanner input=new Scanner(System.in);
		for(int i=0;i<3;i++)
			for(int j=0;j<3;j++)
			    a[i][j]=input.nextInt();
 
		System.out.println("Enter the second matrix:");
		for(int i=0;i<3;i++)
			for(int j=0;j<3;j++)
				b[i][j]=input.nextInt();
		System.out.println("Matrix multiplication is as follows:");
		for(int i=0;i<3;i++)
		{
			for(int j=0;j<3;j++)
			{
				c[i][j]=0;
				for(int k=0;k<3;k++)
				{
				  c[i][j]+=a[i][k]*b[k][j];
	           			}
			}
	    	}
	    	for(int i=0;i<3;i++)
			{
			for(int j=0;j<3;j++)
	 		{
	     		System.out.print(a[i][j]+"\t");
    			}
    			System.out.println("\n");
        		}
        		System.out.println("\n");
        		for(int i=0;i<3;i++)
			{
			for(int j=0;j<3;j++)
	 		{
	     		System.out.print(b[i][j]+"\t");
    			}
    			System.out.println("\n");
        		}	
        		System.out.println("\n");
	    	for(int i=0;i<3;i++)
			{
			for(int j=0;j<3;j++)
	 		{
	     		System.out.print(c[i][j]+"\t");
    			}
    			System.out.println("\n");
        		}		   	
	}
}

Output:

Enter the first matrix:
1 2 3 4 5 6 7 8 9

Enter the second matrix:
9 8 7 6 5 4 3 2 1

Matrix multiplication is as follows:
1 2 3
4 5 6
7 8 9

9 8 7
6 5 4
3 2 1

30 24 18
84 69 54
138 114 90

Avatar of Ranjith

Author Name :
Ranjith

Total : 7 Comments


7 Responses to “Java Program to multiply two matrices”

  1. jenita says:

    hmmm…..d program is gud but i didn’t knw dat der is a method called scanner….i am an icse student nd i am learnin java at school….i am new to this java environmnt…..anyway its gud…!!!! (^.^)….

  2. sam says:

    hello…. d program is quite gud…. and i really hate computer apps…..it is compulsary to learn java in our school ….and ur program was of immense help….i hav mycomputer apps exam 2mrw….!!!! ….thankzz….

  3. Faustina says:

    It is very useful for my university exam. Thank you very much… I am studying B.Sc Computer Science. I am very interested in java

  4. usama says:

    It is very useful!
    thanks for sharing

  5. sathish says:

    thanks

  6. yash says:

    thanks dude for sharing you see i am an 11 grader of icse and i think i’ll be in need for your further help

  7. Sourav Saha says:

    Can i get the algorithms??

Leave a Reply

Question and Answer
C/C++ Unix & Linux Wordpress
Source codes
C C++ Java

Free email signup

Email: