Saturday, January 31, 2015

Gaussian Elimination

The following C program finds the solution to system of linear equations using Gaussian Elimination, given there exists a unique solution to the problem
#include <stdio.h>
#include <stdlib.h>
int no;
double **A, *B, *x;
void Gauss(int n) {
    int r, c, d=no-n;
 
    if(n != 1) {
        for(r=d+1; r < no; r++) {
            for(c=d+1; c<no; c++)
                A[r][c] -= A[r][d]/A[d][d] * A[d][c];
            B[r] -= A[r][d]/A[d][d] * B[d];
            A[r][d]=0;
        }
        Gauss(n-1);
    }
 
    for(c=d+1; c<no; c++)
        B[d] -= A[d][c]*x[c];
    x[d] = B[d]/A[d][d];
}
void acceptNsolve() {
    int r, c;
    printf("Enter the no of unknowns\n");
    scanf("%d", &no);
    printf("Enter the coefficient matrix\n");
    A=malloc(no);
    for(r=0; r<no; r++) {
        A[r] = malloc(no * sizeof(double));
        for(c=0; c<no; c++)
            scanf("%lf", &A[r][c]);
    }
    printf("Enter value of constants in the column vector\n");
    B = malloc(no * sizeof(double));
    for(r=0; r<no; r++)
        scanf("%lf", &B[r]); 
    x = malloc(no * sizeof(double));
    Gauss(no);
    printf("The solution of the given linear equations is\n");
    for(r=0; r<no; r++)
        printf("%g\n",x[r]);
}
int main() {
    acceptNsolve();
    return 0;
}
Input:
Enter the no of unknowns
3
Enter the coefficient matrix
5 3 1
2 1 3
1 2 4
Enter value of constants in the column vector
16 19 25

Output:
The solution of the given linear equations is
1
2
5

No comments:

Post a Comment