Skip to content

Instantly share code, notes, and snippets.

@gnarula
Created February 23, 2012 17:28
Show Gist options
  • Save gnarula/1893919 to your computer and use it in GitHub Desktop.
Save gnarula/1893919 to your computer and use it in GitHub Desktop.
Multiply two n*n matrices
/*
* 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