You are on page 1of 3

/*------------------------------Assignment 13

--------------------------------------
* Aim: To solve simultaneous linear equations using Gauss Elimination
*
* Program developed by Sourabh Raj Jaiswal
*/

import java.io.*;

class Assignment_13
{
static void sol(double G[][], double A[] )
{
int n = A.length;//storring the size of array
int max,i,j,k,l;
double div,t,sum;
for(k=0;k<n;k++)
{
max =k;
for(i=k+1;i<n;i++)
{
if(Math.abs(G[i][k])>Math.abs(G[max][k]))
{
max=i;
}

}
//swapping row in A matrix
double tmp[] = G[k];
G[k] = G[max];
G[max] = tmp;

//swapping corresponding values in constants' matrix


t=A[k];
A[k] = A[max];
A[max] = t;

for(i = k+1;i<n;i++)
{
div = G[i][k]/G[k][k];
A[i] = A[i] - (div*A[k]);
for(j=k;j<n;j++)
{
G[i][j] = G[i][j] - div*G[k][j];
}
}
}

//back substitution
double ans[] = new double[n];
for(i=n-1;i>=0;i--)
{
sum = 0.0;
for(j = i+1;j<n;j++)
{
sum = sum + G[i][j] * ans[j];
}
ans[i] = (A[i]-sum)/G[i][i];
}
l=ans.length;

System.out.println("Solution: ");
for(i =0;i<n;i++)
{
System.out.printf("%.2f " ,ans[i]);
System.out.print("\t");
}
}

static void display(double G[][], double A[])


{
int n = A.length;
System.out.println("The Matrix in Row Form: ");
for(int i = 0; i<n;i++)
{
for(int j =0;j<n;j++)
{
System.out.printf("%.2f " ,G[i][j]);
System.out.print("\t");
}
System.out.printf("| %.2f\n" ,A[i]);
}
System.out.println();
}

public static void main() throws IOException


{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n;
int error = 0;
do
{
error=0;
System.out.println("Enter the number of variables(between 2 and 5)");
n= Integer.parseInt(br.readLine());
if(n<2 || n>5)
{
System.out.println("Invalid Entry.");
error=1;
}

}while(error==1);
double A[] = new double[n];
double G[][] = new double[n][n];
System.out.println("Enter the coefficients");
for(int i = 0; i<n;i++)
{
System.out.println("Enter coefficients of equation "+(i+1));
for(int j =0;j<n;j++)
{
G[i][j] = Double.parseDouble(br.readLine());
}
}
for(int i = 0;i<n;i++)
{
System.out.println("Enter the constant term of equation "+(i+1));
A[i] = Double.parseDouble(br.readLine());
}
display(G,A);
sol(G,A);
}
}

You might also like