# A Simple Interactive Program that Can Solve A Linear System of Equations

So I was just reading my algebra-precalculus textbook, and learned that matrices can be used to solve systems of equations. Since the whole process seemed so algorithmic, I wondered if I could implement it as a program. The result is the following:

/*
*
* Solve a system of equations in two variables, x and y
*
*/

#include <iostream>

struct LinearEquation
{
double xCoefficient;
double yCoefficient;
double constantTerm;
};

struct Solution
{
double x;
double y;
};

double findDeterminant(const LinearEquation& a, const LinearEquation& b);
Solution solveEquation(const LinearEquation& a, const LinearEquation& b, double determinant);

int main()
{
std::cout << "Welcome to the linear equation solver! Enter the following inputs for two equations of the form ax + by = c.\n\n";

LinearEquation one, two;

std::cout << "Equation #1\n";

std::cout << "Equation #2\n";

double det = findDeterminant(one, two);
if (det != 0)
{
Solution solution = solveEquation(one, two, det);
std::cout << "The solution:\n";
std::cout << "x = " << solution.x << "\n";
std::cout << "y = " << solution.y << "\n";
}
else
{
std::cout << "This linear equation has no unique solutions!\n";
}
}

{
LinearEquation result;
std::cout << "X coefficient: ";
std::cin >> result.xCoefficient;
std::cout << "Y coefficient: ";
std::cin >> result.yCoefficient;
std::cout << "Constant term: ";
std::cin >> result.constantTerm;

return result;
}

double findDeterminant(const LinearEquation& a, const LinearEquation& b)
{
return a.xCoefficient * b.yCoefficient - a.yCoefficient * b.xCoefficient;
}

Solution solveEquation(const LinearEquation& a, const LinearEquation& b, double determinant)
{
// Calculating the inverse
double matrixTL = b.yCoefficient / determinant;
double matrixTR = -1 * (a.yCoefficient / determinant);
double matrixBL = -1 * (b.xCoefficient / determinant);
double matrixBR = a.xCoefficient / determinant;

Solution result;
// Matrix multiplication
result.x = matrixTL * a.constantTerm + matrixTR * b.constantTerm;
result.y = matrixBL * a.constantTerm + matrixBR * b.constantTerm;

return result;
}


This program simply goes through each coefficient and constant term and basically applies a "formula" to solve the equation. It works as far, but it could have minor bugs. I am looking for ways this program can be improved in terms of program size or efficiency. Another problem I want to solve is in terms to making this program handle more equations/variables, which would currently require manually adding parts of the matrix.