Simplex Method in C++
#include <iostream>
#include <vector>
#include <iomanip>
using namespace std;
void printTable(const vector<vector<double>> &table) {
cout << fixed << setprecision(2);
for (const auto &row : table) {
for (double val : row) {
cout << setw(10) << val << " ";
cout << endl;
cout << endl;
void simplexMethod(vector<vector<double>> table, int numVariables, int numConstraints) {
while (true) {
// Find entering variable (most negative coefficient in objective function row)
int enteringCol = -1;
double minVal = 0.0;
for (int j = 0; j < numVariables + numConstraints; j++) {
if (table[0][j] < minVal) {
minVal = table[0][j];
enteringCol = j;
if (enteringCol == -1) {
// Optimal solution found
cout << "Optimal solution reached.\n";
break;
// Find leaving variable (minimum positive ratio of RHS to entering column)
int leavingRow = -1;
double minRatio = 1e9;
for (int i = 1; i <= numConstraints; i++) {
if (table[i][enteringCol] > 0) {
double ratio = table[i][numVariables + numConstraints] /
table[i][enteringCol];
if (ratio < minRatio) {
minRatio = ratio;
leavingRow = i;
if (leavingRow == -1) {
cout << "Unbounded solution.\n";
return;
}
// Pivoting
double pivot = table[leavingRow][enteringCol];
for (int j = 0; j <= numVariables + numConstraints; j++) {
table[leavingRow][j] /= pivot;
for (int i = 0; i <= numConstraints; i++) {
if (i != leavingRow) {
double factor = table[i][enteringCol];
for (int j = 0; j <= numVariables + numConstraints; j++) {
table[i][j] -= factor * table[leavingRow][j];
cout << "Table after pivoting:\n";
printTable(table);
cout << "Optimal solution:\n";
for (int j = 0; j < numVariables; j++) {
double value = 0.0;
for (int i = 1; i <= numConstraints; i++) {
if (table[i][j] == 1.0) {
value = table[i][numVariables + numConstraints];
break;
cout << "x" << (j + 1) << " = " << value << endl;
cout << "Z = " << table[0][numVariables + numConstraints] << endl;
int main() {
int numVariables, numConstraints;
cout << "Enter the number of variables: ";
cin >> numVariables;
cout << "Enter the number of constraints: ";
cin >> numConstraints;
vector<vector<double>> table(numConstraints + 1, vector<double>(numVariables +
numConstraints + 1, 0.0));
cout << "Enter the coefficients of the objective function (Z):\n";
for (int j = 0; j < numVariables; j++) {
cin >> table[0][j];
table[0][j] *= -1; // Convert maximization to minimization
cout << "Enter the coefficients of the constraints:\n";
for (int i = 1; i <= numConstraints; i++) {
for (int j = 0; j < numVariables; j++) {
cin >> table[i][j];
table[i][numVariables + i - 1] = 1.0; // Add slack variables
cin >> table[i][numVariables + numConstraints]; // RHS values
cout << "Initial Simplex Table:\n";
printTable(table);
simplexMethod(table, numVariables, numConstraints);
return 0;