STANAANDREY

gauss elimination

Sep 20th, 2019
194
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.35 KB | None | 0 0
  1. //Gauss Elimination
  2. #include <bits/stdc++.h>
  3. using namespace std;
  4. int main()
  5. {
  6.     int n,i,j,k;
  7.     cout.precision(4);        //set precision
  8.     cout.setf(ios::fixed);
  9.     cout<<"\nEnter the no. of equations\n";
  10.     cin>>n;                //input the no. of equations
  11.     float a[n][n+1],x[n];        //declare an array to store the elements of augmented-matrix
  12.     cout<<"\nEnter the elements of the augmented-matrix row-wise:\n";
  13.     for (i=0;i<n;i++)
  14.         for (j=0;j<=n;j++)
  15.             cin>>a[i][j];    //input the elements of array
  16.     for (i=0;i<n;i++)                    //Pivotisation
  17.         for (k=i+1;k<n;k++)
  18.             if (abs(a[i][i])<abs(a[k][i]))
  19.                 for (j=0;j<=n;j++)
  20.                 {
  21.                     swap(a[i][j], a[k][j]);
  22.                 }
  23.     cout<<"\nThe matrix after Pivotisation is:\n";
  24.     for (i=0;i<n;i++)            //print the new matrix
  25.     {
  26.         for (j=0;j<=n;j++)
  27.             cout<<a[i][j]<<setw(16);
  28.         cout<<"\n";
  29.     }
  30.     for (i=0;i<n-1;i++)            //loop to perform the gauss elimination
  31.         for (k=i+1;k<n;k++)
  32.             {
  33.                 double t=a[k][i]/a[i][i];
  34.                 for (j=0;j<=n;j++)
  35.                     a[k][j]=a[k][j]-t*a[i][j];    //make the elements below the pivot elements equal to zero or elimnate the variables
  36.             }
  37.  
  38.     cout<<"\n\nThe matrix after gauss-elimination is as follows:\n";
  39.     for (i=0;i<n;i++)            //print the new matrix
  40.     {
  41.         for (j=0;j<=n;j++)
  42.             cout<<a[i][j]<<setw(16);
  43.         cout<<"\n";
  44.     }
  45.     for (i=n-1;i>=0;i--)                //back-substitution
  46.     {                        //x is an array whose values correspond to the values of x,y,z..
  47.         x[i]=a[i][n];                //make the variable to be calculated equal to the rhs of the last equation
  48.         for (j=i+1;j<n;j++)
  49.             if (j!=i)            //then subtract all the lhs values except the coefficient of the variable whose value                                   is being calculated
  50.                 x[i]=x[i]-a[i][j]*x[j];
  51.         x[i]=x[i]/a[i][i];            //now finally divide the rhs by the coefficient of the variable to be calculated
  52.     }
  53.     cout<<"\nThe values of the variables are as follows:\n";
  54.     for (i=0;i<n;i++)
  55.         cout<<x[i]<<endl;            // Print the values of x, y,z,....
  56.     return 0;
  57. }
Add Comment
Please, Sign In to add comment