Solution of system of linear equation by Gauss-Jordan elimination process. #include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
int main()
{
double *coeff[15],*b,x1,x2,x3,*solution,temp,str,temp1;
int i,j,ROW,k,nz,p,q;
printf("\n Enter the value of row OR coloumn:");
scanf("%d",&ROW);
for(i=0;i<ROW;i++)
coeff[i]=(double *)malloc(ROW*sizeof(double));
solution=(double *)malloc((ROW+1)*sizeof(double));
b=(double *)malloc(ROW*sizeof(double));
printf("\n Enter the elements of the coefficient matrix(A):\n");
for(i=0;i<ROW;i++)
{
for(j=0;j<ROW;j++)
scanf("%lf",(coeff[i]+j));
}
printf("\n Enter the elements of the constant matrix:\n");
for(i=0;i<ROW;i++)
{
printf("\n Enter the %dth value:",i+1);
scanf("%lf",(b+i));
}
for(i=0;i<ROW;i++)
coeff[i][ROW]=b[i];
printf("\n The Augumented (A|B) matrix is:\n");
for(i=0;i<ROW;i++)
{
for(j=0;j<=ROW;j++)
printf("%lf ",*(coeff[i]+j));
printf("\n");
}
for(i=0;i<ROW-1;i++)
{
nz=i;
if(*(coeff[i]+i)==0.0)
{
do
{
nz++;
if(nz>=ROW)
{
printf("\n Not solvable by Gauss Jordan:\n");
exit(1);
}
}while(*(coeff[nz]+i)==0.0);
printf("\nnz=%d",nz);
for(k=0;k<=ROW;k++)
{
temp=*(coeff[nz]+k);// temp1=b[nz];
*(coeff[nz]+k)=*(coeff[i]+k);// b[nz]=b[i];
*(coeff[i]+k)=temp;// b[i]=temp1;
}
}
/* printf("\n \n The Augumented (A|b) matrix after Row operations is:\n");
for(p=0;p<ROW;p++)
{
for(q=0;q<ROW;q++)
printf("%lf ",*(coeff[p]+q));
printf("\n");
}*/
for(k=0;k<ROW-i-1;k++)
{
temp=0.0;
str=coeff[i+1+k][i];
//printf("\n str=%lf",str);
//printf("\n pivot=%lf",coeff[i][i]);
for(j=0;j<=ROW;j++)
{
temp=coeff[i+k+1][j];
//printf(" temp=%lf ",temp);
if(str==0.0)
continue;
//temp=temp-((str/coeff[i][i])*coeff[i][j]); temp1=temp1-((str/coeff[i][i])*I[i][j]);
temp=temp/str;
//temp=temp-((temp/str)*coeff[i][i]); temp1=temp1-((str/coeff[i][i])*I[i][j]);
temp=temp*coeff[i][i];
temp=temp-coeff[i][j];
//printf(" [temp=%lf] ",temp);
coeff[i+k+1][j]=temp;
}
}
}
printf("\n The Augumented (A|B) matrix after Row operations is:\n");
for(i=0;i<ROW;i++)
{
for(j=0;j<=ROW;j++)
printf("%lf ",*(coeff[i]+j));
printf("\n");
}
for(i=ROW;i>0;i--)
{
if(i==ROW)
solution[i]=(*(coeff[i-1]+i)/ *(coeff[i-1]+i-1));
else
{
temp=0.0;
nz=ROW-i;
j=ROW;
for(k=1;k<=nz;k++)
{
temp += coeff[i-1][j-1]*solution[j];
//printf("coeff[%d,%d]*solution[%d]\n",i-1,j-1,j);
j--;
}
temp=coeff[i-1][ROW]-temp;
solution[i]=(temp/coeff[i-1][i-1]);
}
}
printf("\n The solution by Gauss-Jordan elimination process is:\n");
for(i=1;i<=ROW;i++)
printf("x[%d]=%lf ",i,solution[i]);
printf("\n");
return 0;
}
No comments:
Post a Comment