Monday, August 24, 2015

Program for Gauss-Jordan Elimination without frills

#include <iostream>
#include <cmath>
using namespace std;
                
int main ()
{

        int a,z,i,j;
        cout << "Enter the number of equations \n";
        cin >> a;
        float ar [a][a+1];
        
        cout << "Entering the elements of the array \n";
        for (i=0;i<a;i++)
        {        
        for (j=0; j<(a); j++)
        {
        if (i==j)
        {
         ar[i][j] = 2;
        }
        else if(i!=j)
        {
        ar[i][j] = -1;
        }
        }
        }

        for (i=0;i<a;i++)
        {
        ar[i][a] = -97;
        }

        

        
        cout << " \n\n GAUSS JORDAN ELIMINATION \n";
        float temp,max;        
        int k,l;
        
        for (i=0;i <a; i++)
        {
        max = ar[i][i]; 
        k=i;
        for (j=i;j <a; j++)
        {
        
        
        if (abs(ar[j][i]) > abs(max))        
        {
        
        
        max = ar[j][i];
        
        k=j;
        
        }
        }
        
        for (l=0;l<a+1;l++)
        {
        
        temp = ar[i][l];
        ar[i][l] = ar[k][l];
        ar[k][l] = temp;
        
        }
        
        
        

        
        int x,y;
        float z, rat;
        z = ar[i][i]; 
        
        if (z != 0)
        {
        for (x=i+1; x <a; x++)
        {
        
        rat = (ar[x][i]) / (ar[i][i]);        
        
        for (y=0;y<a+1;y++)
        {
        ar[x][y] = ar[x][y] - (rat*ar[i][y]);
        }
        }
        }

        
        }
        
        int ab;
        float x[a];
        for (ab=(a-1);ab>-1;ab--)
        {
         x[ab]=ar[ab][a];
        
        for (i=ab+1;i<a;i++)
        {
        x[ab]=x[ab]-(ar[ab][i]*x[i]);
        }
        x[ab] = (x[ab]/ar[ab][ab]);
        
        }
        

        for (i=0;i<a;i++)
        {
        cout << "x["<<i<<"] \t= " << x[i] <<endl;
        }
        
return 0;
        }