Advertisement
Arnab_Manna

GaussJordanElimination

Sep 10th, 2020
164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.64 KB | None | 0 0
  1. #include<conio.h>
  2. #include<stdio.h>
  3. #include<stdlib.h>
  4. #define Max 100
  5. #define TRUE 1
  6. #define FALSE 0
  7. typedef unsigned char Boolean;
  8. void ReadMat(float A[Max][Max+1],int n)
  9. {
  10.     int i,j;
  11.     for(i=0;i<n;i++)
  12.     for(j=0;j<(n+1);j++)
  13.     scanf("%f",&A[i][j]);
  14. }
  15. void PrintMat(float A[Max][Max+1], int n)
  16. {
  17. int i,j;
  18. for(i=0;i<n;i++)
  19. {
  20. for(j=0;j<(n+1);j++)
  21. printf("%10.3f ",A[i][j]);
  22. printf("\n");
  23. }
  24. }
  25. Boolean GaussJordanElimination(float A[Max][Max+1],int n)
  26. {
  27.     float C1,Det=1;
  28.     int i,j,k;
  29.     for(i=0;i<n;i++)
  30.     {
  31.         if(A[i][i]==0) //checking if zero or not
  32.         {
  33.             PrintMat(A,n);
  34.             printf("\n");
  35.             for(k=i+1;k<n;k++)//search for non zero row of matrix
  36.             if(A[k][i]!=0)break;
  37.             if(k>=n)return FALSE;
  38.             for(j=i;j<(n+1);j++)
  39.             {
  40.                 C1=A[i][j];
  41.                 A[i][j]=A[k][j];
  42.                 A[k][j]=C1;
  43.             }
  44.             PrintMat(A,n);
  45.             printf("\n");
  46.         }
  47.         C1=A[i][i];
  48.         Det=Det*C1;
  49.         for(j=i;j<(n+1);j++)//pivoting the ith row
  50.             A[i][j]=A[i][j]/C1;
  51.             PrintMat(A,n);
  52.             printf("\n");
  53.         for(k=0;k<n;k++)//eleminate all rows from ith to nth row
  54.         {
  55.             if(k==i)
  56.             continue;
  57.             C1=A[k][i];//take a[k][i] as multliplication constant
  58.             for(j=i;j<(n+1);j++)//elemminate
  59.             A[k][j]=A[k][j]-(A[i][j]*C1);
  60.             PrintMat(A,n);
  61.             printf("\n");
  62.         }
  63.     }
  64.     printf("\nDet=%f",Det);
  65. return TRUE;
  66. }
  67. int main()
  68. {
  69.     float A[Max][Max+1],X[Max];
  70.     int i,n;
  71.     printf("enter the number of rows : ");
  72.     scanf("%d",&n);
  73.     ReadMat(A,n);
  74.     PrintMat(A,n);
  75.     printf("\n");
  76.     if(GaussJordanElimination(A,n))
  77.     {
  78.         for(i=0;i<n;i++)
  79.         X[i]=A[i][n];
  80.         printf("\nSolution");
  81.         for(i=0;i<n;i++)
  82.         printf("\nX[%d]=%f",i,X[i]);
  83.     }
  84.     else
  85.     printf("\nno solution present");
  86.     return 0;
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement