Problem
Write a c program to find determinant of a matrix, the size should be variable
#include<stdio.h>
#include<stdlib.h>
int size;
float fact(float **data,int sz);
void extract(float **data,float **temp,int a,int sz);
float** scan(float **data);
int main()
{
printf("enter the size of the matrix ");
scanf("%d",&size);
float **data,ans;
data=scan(data);
ans=fact(data,size);
printf("determinant of matrix is=%f",ans);
}
float fact(float **data,int sz)
{
float ans=0;
int i;
if(sz==2)
{
return data[0][0]*data[1][1]-data[0][1]*data[1][0];
}
else
{
float **temp;
temp=(float**)malloc((sz-1)*sizeof(float*));
for(i=0;i<sz-1;i++)
temp[i]=(float*)malloc((sz-1)*sizeof(float));
for(i=0;i<sz;i++)
{
extract(data,temp,i,sz);
if(i%2==0)
{
ans=ans+data[0][i]*fact(temp,sz-1);
}
else
{
ans=ans-data[0][i]*fact(temp,sz-1);
}
}
}
return ans;
}
void extract(float **data,float **temp,int a,int sz)
{
int i,j,i_f,r_f;
i_f=0;
for(i=1;i<sz;i++)
{
r_f=0;
for(j=0;j<sz;j++)
{
if(j!=a)
{
temp[i_f][r_f]=data[i][j];
r_f++;
}
}
i_f++;
}
}
float** scan(float **data)
{
int i,j;
data=(float**)malloc(size*sizeof(float*));
printf("enter values rowwise")
for(i=0;i<size;i++)
{
data[i]=(float*)malloc(size*sizeof(float));
for(j=0;j<size;j++)
{
scanf("%f",&data[i][j]);
}
}
return data;
}
Write a c program to find determinant of a matrix, the size should be variable
#include<stdio.h>
#include<stdlib.h>
int size;
float fact(float **data,int sz);
void extract(float **data,float **temp,int a,int sz);
float** scan(float **data);
int main()
{
printf("enter the size of the matrix ");
scanf("%d",&size);
float **data,ans;
data=scan(data);
ans=fact(data,size);
printf("determinant of matrix is=%f",ans);
}
float fact(float **data,int sz)
{
float ans=0;
int i;
if(sz==2)
{
return data[0][0]*data[1][1]-data[0][1]*data[1][0];
}
else
{
float **temp;
temp=(float**)malloc((sz-1)*sizeof(float*));
for(i=0;i<sz-1;i++)
temp[i]=(float*)malloc((sz-1)*sizeof(float));
for(i=0;i<sz;i++)
{
extract(data,temp,i,sz);
if(i%2==0)
{
ans=ans+data[0][i]*fact(temp,sz-1);
}
else
{
ans=ans-data[0][i]*fact(temp,sz-1);
}
}
}
return ans;
}
void extract(float **data,float **temp,int a,int sz)
{
int i,j,i_f,r_f;
i_f=0;
for(i=1;i<sz;i++)
{
r_f=0;
for(j=0;j<sz;j++)
{
if(j!=a)
{
temp[i_f][r_f]=data[i][j];
r_f++;
}
}
i_f++;
}
}
float** scan(float **data)
{
int i,j;
data=(float**)malloc(size*sizeof(float*));
printf("enter values rowwise")
for(i=0;i<size;i++)
{
data[i]=(float*)malloc(size*sizeof(float));
for(j=0;j<size;j++)
{
scanf("%f",&data[i][j]);
}
}
return data;
}
No comments:
Post a Comment