Saturday, 8 February 2014

Cramer's Rule C program using 2d array

/*Okay this is the second time typing this as i closed internet explorer on accident before posting!! ahh! anyways, im new to this forum, although not new to programming, ive been programming almost 4 months now. Im having trouble with this final program for class. It is involving cramer's rule, using matrix functions instead of classic algebra. The program is up and running, yet it produces the wrong results. Ive checked and rechecked the code as well as the prototype function expansion and everything looks good, however the results are not correct. Given this example 3x3 matrix below, the program should prduce the unqiue solution (0.5, 0.5, -1.5). The 4th column is (b1,b2,and b3) respectivley.

PLEASE KEEP IN MIND THAT WE ARE PROGRAMMING IN C, NOT C++
This should be obvious given the .h headers.

Example 3x3 Matrix input:

3 1 2 -1
2 -1 1 -1
0 5 5 -5

Unique solution : (0.5,0.5,-1.5)*/
printf(" it me ameer hamza/n letsdoprogramminginc.blogspot.com \n this is my blog");
#include <stdio.h>
int det3(int a[3][3]);

int main(void)
{

    int A[3][3];
    int B[3];

 printf("this code by ameer hamza\n");
 //printf("this code by ameer hamza\n");

    printf("This program uses Cramer's Rule to solve a linear system\n.");

            printf("Enter each of 3 linear equations as four integers separated by space.\n");

        printf("For example, x - 2y + 3z = 4 should be entered as 1 -2 3 4\n");

    printf("\n\nEnter equation 1: ");

    scanf("%i %i %i %i", &A[0][0], &A[0][1], &A[0][2], &B[0]);

    printf("Enter equation 2: ");

    scanf("%i %i %i %i", &A[1][0], &A[1][1], &A[1][2], &B[1]);

    printf("Enter equation 3: ");

    scanf("%i %i %i %i", &A[2][0], &A[2][1], &A[2][2], &B[2]);
    /*Finding determinants*/
int detx[3][3] = {{B[0],A[0][1],A[0][2]},{B[1],A[1][1],A[1][2]},
{B[2],A[2][1],A[2][2]}};

    int dety[3][3] = {{A[0][0],B[0],A[0][2]},{A[1][0],B[1],A[1][2]},

                          {A[2][0],B[2],A[2][2]}};

    int detz[3][3] = {{A[0][0],A[0][1],B[0]},{A[1][0],A[1][1],B[1]},

                          {A[2][0],A[2][1],B[2]}};

      if(det3(A)!=0)

             printf("\nSystem has a unique solution ( %d, %d, %d)",

             det3(detx)/det3(A), det3(dety)/det3(A), det3(detz)/det3(A));

      else

             printf("\nSystem does not have a unique solution because determinant is 0");
    return 0;
}
int det3(int a[3][3])
{
    return (a[0][0]*a[1][1]*a[2][2])-(a[0][0]*a[1][2]*a[2][1]),

                +(a[0][1]*a[1][2]*a[2][0])-(a[0][1]*a[1][0]*a[2][2]),

                +(a[0][2]*a[1][0]*a[2][1])-(a[0][2]*a[1][1]*a[2][0]);

}

No comments:

Post a Comment