Sunday, September 11, 2011

Find the inverse of given matrix using malloc function


#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main()
{
float **a,*temp,temp1;
int i,j,k,n;
float **b;
printf("enter the order of matrix:");
scanf("%d",&n);

a=(float**)malloc(n*sizeof(float *));
for(i=0;i<n;i++)
a[i]=(float *)malloc(n*sizeof(float));
b=(float**)malloc(n*sizeof(float *));
for(i=0;i<n;i++)
b[i]=(float *)malloc(n*sizeof(float));
temp=(float *)malloc(n*sizeof(float));
for(i=0;i<n;i++)
{
 for(j=0;j<n;j++)
 {
  if(j==i)
  b[i][i]=1;
  else
  b[i][j]=0;
 }
}

printf("\n Enter the matrix\n");
for(i=0;i<n;i++)
{
 printf("\nEnter the %dth row \n",i);
 for(j=0;j<n;j++)
 {
  scanf("%f",&a[i][j]);
 }
}

printf("\nEntered a matrix:\n");
for(i=0;i<n;i++)
{
 for(j=0;j<n;j++)
 {
  printf(" %.2f",a[i][j]);
 }
 printf("\n");
}

for(i=0;i<n;i++)
{
     for(k=0;k<n;k++)
     {
       if(k!=i)
       {
for(j=0;j<n;j++)
{
 if(a[i][j]==a[k][j])
   continue;
          else
            break;
}
         if(j==n)
        {
     printf("\nDuplicate row\n");
     getch();
      exit(0);
        }
  }
     }
 
if(a[i][i]==0)
{
     for(k=i+1;k<n;k++)
     {
       if(a[k][i]!=0)
       {
for(j=0;j<n;j++)
{
 temp1=a[i][j];
 a[i][j]=a[k][j];
 a[k][j]=temp1;
 temp1=b[i][j];
 b[i][j]=b[k][j];
 b[k][j]=temp1;
}

break;
       }
     }
     if(k==n)
     {
 printf("\nInvalid entry\n");
 getch();
 exit(0);
     }
}

temp1=a[i][i];
  for(j=0;j<n;j++)
   {
    a[i][j]=a[i][j]/temp1;
    b[i][j]=b[i][j]/temp1;
   }

   for(j=0;j<n;j++)
   {
     if(j!=i)
     {
temp[j]=a[j][i];
     }
   }

    for(k=0;k<n;k++)
    {
    for(j=0;j<n;j++)
    {
    if(k!=i)
    {
     a[k][j]=a[k][j]-(temp[k]*a[i][j]);
     b[k][j]=b[k][j]-(temp[k]*b[i][j]);
    }
    }
    }

}

printf("\n Inverse matrix:\n");
for(i=0;i<n;i++)
{
 for(j=0;j<n;j++)
 {
  printf("  %.2f",b[i][j]);
 }
 printf("\n");
}
printf("\n matrix A after calculation:\n");
for(i=0;i<n;i++)
{
 for(j=0;j<n;j++)
 {
  printf("  %.2f",a[i][j]);
 }
 printf("\n");
}

getch();
}

Previous Next Home
2 Comments
Comments

Leave a Comment

:)) ;)) ;;) :D ;) :p :(( :) :( :X =(( :-o :-/ :-* :| 8-} :)] ~x( :-t b-( :-L x( =))

Twitter Delicious Facebook Favorites More