Created
February 23, 2012 17:28
-
-
Save gnarula/1893919 to your computer and use it in GitHub Desktop.
Multiply two n*n matrices
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Multiplies two n*n matrices. | |
* | |
* @author Gaurav Narula | |
* */ | |
import java.util.Scanner; | |
public class matrix { | |
private int[][] arr; | |
private int n; | |
public matrix(int n){ | |
this.n = n; | |
arr = new int[n][n]; | |
} | |
public void multiply(matrix ob) { | |
if(ob.n != this.n) { | |
System.out.println("Matrices should be of same order"); | |
return; | |
} | |
int[][] product = new int[n][n]; | |
for(int i = 0; i < n; i++) { | |
for(int j = 0; j < n; j++) { | |
int sum = 0; | |
for(int k = 0; k < n; k++) { | |
sum = sum + arr[i][k] * ob.arr[k][j]; | |
} | |
product[i][j] = sum; | |
} | |
} | |
display(product); | |
} | |
public void display(int[][] x) { | |
for(int i = 0; i < n; i++) { | |
for(int j = 0; j < n; j++) { | |
System.out.print(x[i][j] + " "); | |
} | |
System.out.println(); | |
} | |
} | |
Scanner scan = new Scanner(System.in); | |
public void input() { | |
for(int i = 0; i < n; i++) { | |
for(int j = 0; j < n; j++) { | |
System.out.println("Enter value for row " + i + " column " + j); | |
arr[i][j] = scan.nextInt(); | |
} | |
} | |
} | |
public static void main(String[] args) { | |
matrix ob = new matrix(3); | |
ob.input(); | |
matrix ob2 = new matrix(3); | |
ob2.input(); | |
ob.multiply(ob2); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment