4. Write a program to demonstrate Gauss Elimination Method.
/*Program to execute Gauss Elimination method */
#include <stdio.h>
#include <math.h>
#include <conio.h>
#define max 10
void main()
{
int i, j, k, n;
float t = 0, sol, a[max][max + 1], x[max];
clrscr();
printf("Enter number of equations\n");
scanf("%d", &n);
printf("Input data for arugement matrix: \n");
for (i = 0; i < n; i++)
{
for (j = 0; j <= n; j++)
{
scanf("%f", &a[i][j]);
}
}
for (j = 0; j < n - 1; j++)
{
for (i = j + 1; i < n; i++)
{
t = a[i][j] / a[j][j];
for (k = 0;
k <= n;
k++)
{
a[i][k] = a[i][k] - a[j][k] * t;
}
}
}
printf("\n The upper triangular matrix is: \n");
for (i = 0; i < n; i++)
{
for (j = 0; j <= n; j++)
{
printf("%f\t", a[i][j]);
}
printf("\n");
}
for (i = 0; i < n; i++)
x[i] = 0;
for (i = n - 1; i >= 0; i--)
{
sol = 0;
for (j = 0; j < n; j++)
{
sol = sol + a[i][j] * x[j];
}
x[i] = (a[i][n] - sol) / a[i][i];
}
printf("\n\n The solution is: ");
for (i = 0; i < n; i++)
{
printf("\nElement %d: %f: ", i + 1, x[i]);
}
getch();
}
Output
Enter number of equations
4
Input data for augmented matrix:
10 -7 3 5 6
-6 8 -1 -4 5
3 1 4 11 2
5 -9 -2 4 7
The upper triangular matrix is:
10.000000 -7.000000 3.000000 5.000000 6.000000
0.000000 3.800000 0.800000 -1.000000 8.600000
-0.000000 -0.000000 2.447368 10.315789 -6.815791
0.000000 -0 .000000 -0.000000 9.924731 9.924738
The solutions is:
Element 1: 5.000001
Element 2: 4.000001
Element 1: -7.000001
Element 1: 1.000001