Systems of Linear Equations: Solving by Gaussian Elimination

  1. #include < stdio.h >  
  2. #include < conio.h >   
  3. int main(void)   
  4. {  
  5.     void backsubs(float[][10], float[], int);  
  6.     float a[10][10], b[10], tem = 0, temp = 0, temp1 = 0, temp2 = 0, temp4 = 0, temp5 = 0;  
  7.     int n = 0, m = 0, i = 0, j = 0, p = 0, q = 0;  
  8.     printf("Enter size of 2d array(Square matrix) : ");  
  9.     scanf("%d", & n);  
  10.     for (i = 0; i < n; i++)   
  11.     {  
  12.         for (j = 0; j < n; j++)   
  13.         {  
  14.             printf("Enter values no. %d %d :", i, j);  
  15.             scanf("%f", & a[i][j]);  
  16.         }  
  17.     }  
  18.     printf("\nEnter Values to the right side of equation\n");  
  19.     for (i = 0; i < n; i++)  
  20.     {  
  21.         printf("Enter values no. %d :", i, j);  
  22.         scanf("%f", & b[i]);  
  23.     }  
  24.     for (i = 0; i < n; i++)   
  25.     {  
  26.         temp = a[i][i];  
  27.         if (temp < 0) temp = temp * (-1);  
  28.         p = i;  
  29.         for (j = i + 1; j < n; j++)   
  30.         {  
  31.             if (a[j][i] < 0) tem = a[j][i] * (-1);  
  32.             else tem = a[j][i];  
  33.             if (temp < 0) temp = temp * (-1);  
  34.             if (tem > temp)   
  35.             {  
  36.                 p = j;  
  37.                 temp = a[j][i];  
  38.             }  
  39.         }  
  40.         //row exchange in both the matrix  
  41.         for (j = 0; j < n; j++)   
  42.         {  
  43.             temp1 = a[i][j];  
  44.             a[i][j] = a[p][j];  
  45.             a[p][j] = temp1;  
  46.         }  
  47.         temp2 = b[i];  
  48.         b[i] = b[p];  
  49.         b[p] = temp2;  
  50.         //making downwards elements 0 in order to make the matrix a[][] suitable for back substitution  
  51.         temp4 = a[i][i];  
  52.         for (q = i + 1; q < n; q++)   
  53.         {  
  54.             temp5 = a[q][i];  
  55.             for (j = 0; j < n; j++)  
  56.             {  
  57.                 a[q][j] = a[q][j] - ((temp5 / temp4) * a[i][j]);  
  58.             }  
  59.             b[q] = b[q] - (temp5 / temp4 * b[i]);  
  60.         }  
  61.     }  
  62.     backsubs(a, b, n);  
  63.     getch();  
  64.     return 0;  
  65. }  
  66. void backsubs(float a[][10], float b[], int n)  
  67. {  
  68.     int i = 0, j = 0;  
  69.     for (i = n - 1; i >= 0; i--)   
  70.     {  
  71.         for (j = n - 1; j > i; j--)  
  72.         {  
  73.             b[i] = b[i] - a[i][j] * b[j];  
  74.         }  
  75.         b[i] = b[i] / a[i][i];  
  76.         printf("x%d = %f\n", i + 1, b[i]);  
  77.     }