You are on page 1of 4

//SOUVIK & SOUMODIP

A program to solve n no. of simultaneous linear equations entered by the


user( n is user inputed).

import java.io.*;
public class Gausssian_Elimination
{
public static void main() throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("What is the size of the system(n)?????");
int n=Integer.parseInt(br.readLine());
float a[][],b[],x[];
a=new float[n][n];
b=new float[n];
x=new float[n];
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
System.out.print("Enter the element for a["+i+"]["+j+"]");
a[i][j]=Float.parseFloat(br.readLine());
}
}
for(int i=0;i<n;i++)
{
System.out.print("Enter the element for b["+i+"]");
b[i]=Float.parseFloat(br.readLine());
}
gauss(n,a,b,x);
System.out.println("Solution vector for X");
for(int i=0;i<n;i++)
System.out.print(x[i]+" ");
}

public static void gauss(int n,float a[][],float b[],float x[])


{
elimination(n,a,b);
bsub(n,a,b,x);
return;
}

public static void elimination(int n,float a[][],float b[])


{
int i,j,k;
float factor;
for(k=0;k<n-1;k++)
{for(i=k+1;i<n;i++)
{
factor=a[i][k]/a[k][k];
for(j=k+1;j<n;j++)
{
a[i][j]=a[i][j]-factor*a[k][j];
}
b[i]=b[i]-factor*b[k];
}
}
return;
}
public static void bsub(int n,float a[][],float b[],float x[])
{
int i,j,k;
float sum=0;
x[n-1]=b[n-1]/a[n-1][n-1];
for(k=n-1;k>=0;k--)
{
sum=0;
for(j=k+1;j<n;j++)
{sum=sum+a[k][j]*x[j];
}

x[k]=(b[k]-sum)/a[k][k];
}
return;
}
}
SAMPLE OUTPUT:

What is the size of the system(n)?????


3
Enter the element for A[0][0]2
Enter the element for A[0][1]2
Enter the element for A[0][2]1
Enter the element for A[1][0]4
Enter the element for A[1][1]2
Enter the element for A[1][2]3
Enter the element for A[2][0]1
Enter the element for A[2][1]1
Enter the element for A[2][2]1
Enter the element for b[0]6
Enter the element for b[1]4
Enter the element for b[2]0
Solution vector for X
5.0 1.0 -6.0

You might also like