Subscribe to A Kid's scribblings        RSS Feed
-----

Solving 'n' no. of simultaneous linear equations using crammer's rule

Icon Leave Comment
If you don't know crammer's rule check it out at Wikipedia.... If you know and check this out.......

import java.io.*;
public class crammers_rule 
{
    public static void main(String args[])throws Exception
    {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("No of variables to be dealt with ::");
        int n=Integer.parseInt(br.readLine());
        int v[][]=new int[n][n];
        int R[]=new int[n];
        int i,j;
        for(i=0;i<n;i++)
        {
            System.out.println("Equation ::"+(i+1)+"\n");
            for(j=0;j<n;j++)
            {
                System.out.println("Enter the coefficient of variable ::"+(j+1));
                v[i][j]=Integer.parseInt(br.readLine());
            }
            System.out.println("\nEnter the value of the right hand side of equation ::"+(i+1));
            R[i]=Integer.parseInt(br.readLine());
        }
        crammer(v,R,n);
    }
    
    public static void crammer(int v[][],int R[],int n)
 {
     int i=0;
     double res=0;
     for(i=0;i<n;i++)
     {
         res=calculate(v,R,n,i);
         System.out.println("The value of the term "+(i+1)+" :: "+res);
     }
 }
     public static double calculate(int D[][],int R[],int n,int c)
 {
     int i=0,j=0,k=0;
     double res=0.0,d=0.0;
     int t[][]=new int[n][n];
     for(i=0;i<n;i++)
         for(j=0;j<n;j++){
             if(j==c)
             {
                 t[i][j]=R[k++];
             }
             else
                 t[i][j]=D[i][j];
         }
     d=(double)det(D,n);
     res=(double)det(t,n);
     return res/d;
 }
     
 public static int det(int v[][],int n)
 {
    int i=0,t=0,sign=1,sum=0;
    if(n==2){
        t=(v[0][0]*v[1][1])-(v[0][1]*v[1][0]);
        return t;
    }
    else
    {
        for(i=0;i<n;i++)
        {
            sum+=v[0][i]*sign*matrix(v,i,n);
            sign=sign*(-1);
        }
    }
    return sum;
 }
 public static int matrix(int v[][],int c,int n)
 {
     int i=0,j=0,a=0,b=0;
     int t[][]=new int[n-1][n-1];
     for(i=1;i<n;i++)
     {
         b=0;j=0;
         while(j<n)
         {
          if(j==c)
          j++;
          if(j<n)
          t[a][b]=v[i][j];
          j++;
          b++;          
         }
         a++;
     }
     return det(t,n-1);
 }

}

0 Comments On This Entry

 

Recent Comments

August 2014

S M T W T F S
     12
3456789
10111213141516
1718192021 22 23
24252627282930
31      

0 user(s) viewing

0 Guests
0 member(s)
0 anonymous member(s)