| Date Assigned: | Wed Sep-27 |
| Date Due: | Thu Sep-28 |
Your homework tonight is to beautify this code (which we collectively authored in class today) and to make it accept the array size (so long as it's <= MAX_ROWS) and the array values (g_coeffs) as input from the user. You do not have to worry about the case stated in the code when the row's lead coefficient is 0 (big extra credit, though, if you eliminate this nasty bug -- hint: you'll have to "pivot" your rows somehow; hint2: it may not be possible -- not all arrays produce unique solutions!).
Good luck, and don't forget the quiz Friday on C++ arrays.
// gauss.cpp -- Gaussian Elimination
// by David Kosbie and AP Computer Science P8
#include <stdio.h>
#include <iostream.h>
const int MAX_ROWS = 8;
int g_rows = 3; // change to input from user
// change this to be loaded by user
double g_coeffs[MAX_ROWS][MAX_ROWS+1] = {
{-2, 1.5, 4, 2.5},
{1, -1.5, 3, 7.5},
{3, 4.5, -2, 8.5}
};
void reduceCoeffToOne(int row, int col)
{
// ignore case when it is 0 (bug -- fix later)
double divisor = g_coeffs[row][col];
int col2;
for (col2=col; col2<=g_rows; col2++)
g_coeffs[row][col2] = g_coeffs[row][col2] / divisor;
}
void eliminateColumn(int col)
{
// 1. set top left to 1
int row=col;
reduceCoeffToOne(row,col);
// 2. For each row below, eliminate that row using this row
int row2;
for (row2 = col+1; row2 < g_rows; row2++)
{
reduceCoeffToOne(row2,col);
// now subtract row from row2
int col2;
for (col2 = col; col2 <= g_rows; col2++)
g_coeffs[row2][col2] -= g_coeffs[row][col2];
}
}
// if you solve for variable in <row>, then all
// variables in <row2> > <row> must be solved already.
void solveVariable(int row)
{
double answer = g_coeffs[row][g_rows];
int col;
for (col=row+1; col<g_rows; col++)
{
// You must think about this one
answer -= g_coeffs[row][col] * g_coeffs[col][g_rows];
g_coeffs[row][col] = 0;
}
g_coeffs[row][g_rows] = answer;
}
void solveMatrix()
{
int col;
int row;
// eliminate all the columns
for (col=0; col<g_rows; col++)
eliminateColumn(col);
// solve for each variable, BOTTOM UP
for (row=g_rows-1; row>=0; row--)
solveVariable(row);
}
void printAnswers()
{
int row;
cout << "Here are the answers:" << endl;
for (row = 0; row < g_rows; row++)
cout << "x[" << row << "] = "
<< g_coeffs[row][g_rows]
<< endl;
}
void main()
{
cout << "Gaussian Elimination blah blah...";
solveMatrix();
printAnswers();
getchar();
}