determinant of n*n matrix using java code

Here is my code:

import java.util.Scanner.*;
import java.util.*;
public class determinantcode
{

double A[][];
double m[][];
int N;



public input()
{
Scanner s=new Scanner(System.in);
System.out.println("enter dimension of matrix");
N=s.nextInt();
a = new double[N][];
for(int i=0;i<N;i++)
{
A[i]=new double[n];
}

System.out.println("enter the elements of matrix");
for(int i=0;i<N;i++)
{
System.out.println("enter the elements of matrix of equation" + (i+1));
for(int j=0;j<N;j++)
{
int k=s.nextDouble();
A[i][j]=k;
}
}

}
public double determinant(double A[][],int N)
{


double det=0;
double res;


if(N == 1)
res = A[0][0];

else if (N == 2)
{
res = A[0][0]*A[1][1] - A[1][0]*A[0][1];
}

else
{
res=0;
for(int j1=0;j1<N;j1++)
{
m = new double[N-1][];
 for(int k=0;k<(N-1);k++)
   m[k] = new double[N-1];
for(int i=1;i<N;i++)
{
int j2=0;
for(int j=0;j<N;j++)
{
  if(j == j1)
   continue;
  m[i-1][j2] = A[i][j];
  j2++;
}
}
 res += Math.pow(-1.0,1.0+j1+1.0)* A[0][j1] * determinant(m,N-1);


}
}


return res;

}

public static void main(String args[]){
double res;
 determinantcode d = new determinantcode();
  d.input();
  res = d.determinant(d.A,d.N);
  System.out.println("the determinant valaue is  " + res);
 }


}

Thanks

View Answers

April 20, 2011 at 2:30 PM

import java.util.Scanner.*;
import java.util.*;
public class determinantcode
{

double A[][];
double m[][];
int N;

public void input(){
Scanner s=new Scanner(System.in);
System.out.println("enter dimension of matrix");
N=s.nextInt();
A = new double[N][];
for(int i=0;i<N;i++)
{
A[i]=new double[N];
}

System.out.println("enter the elements of matrix");
for(int i=0;i<N;i++)
{
System.out.println("enter the elements of matrix of equation" + (i+1));
for(int j=0;j<N;j++)
{
int k=s.nextInt();
A[i][j]=k;
}
}
}
public double determinant(double A[][],int N){
double det=0;
double res;
if(N == 1)
res = A[0][0];
else if (N == 2){
res = A[0][0]*A[1][1] - A[1][0]*A[0][1];
}
else{
res=0;
for(int j1=0;j1<N;j1++){
m = new double[N-1][];
 for(int k=0;k<(N-1);k++)
   m[k] = new double[N-1];
for(int i=1;i<N;i++){
int j2=0;
for(int j=0;j<N;j++){
  if(j == j1)
   continue;
  m[i-1][j2] = A[i][j];
  j2++;
}
}
 res += Math.pow(-1.0,1.0+j1+1.0)* A[0][j1] * determinant(m,N-1);
}
}
return res;
}
public static void main(String args[]){
double res;
 determinantcode d = new determinantcode();
  d.input();
  res = d.determinant(d.A,d.N);
  System.out.println("the determinant valaue is  " + res);
 }
}









Related Tutorials/Questions & Answers:
Advertisements