Computing: Free Pascal Programming

Balancing chemical equations.

Download chemeq console program (Windows 64bit) Download chemeq source code (Lazarus/Free Pascal)

Description: The program calculates the coefficients of the reactants and products of a chemical reaction in order to balance the equation entered by the user. Enter the (unbalanced) equation using the format:
    reactant1 + reactant2 ... -> product1 + product2 ...
Entering "H" instead, displays a short help text.

Programming notes: The program uses a brute force approach to determine the coefficients. This may result in thousands and thousands of calculations to be done. Whereas for "normal" equations, this doesn't really matter and the answer is more or less instantaneous, for complicated equations, containing 6 molecules and coefficients greater than 10, it may take time. Al + NH4ClO4 -> Al2O3 + AlCl3 + H2O + N2 (balanced: 10Al + 6NH4ClO4 -> 4Al2O3 + 2AlCl3 + 12H2O + 3N2) took some 15 secs on my machine; but these "extreme cases" are very rare in practice.
Coefficients are calculated by generating all size (reactants + products) combinations (including repetitions) of the integers from 1 to a presupposed maximum coefficient value. The program first tries with CoeffMax = 6, then CoeffMax = 12 and finally, if the equation is still not balanced, asks the user if it should continue trying. This has been done to limit calculation time on slower computers, considering that it's rather rare to have equations with coefficient maxima greater than 6.

Version 1.2 (November 2022): Rebuild after possible problems with prior version.

Improvements: Gaining lots of speed by eliminating those combinations which can't be the searched coefficients (e.g. if 1 1 1 1 is not the solution, 2 2 2 2 and 3 3 3 3 can't be either). Another way to limit the number of calculations would be to sort the combinations differently (2 2 3 1 is lots more probable than 1 1 1 12...)

Free Pascal features: Recursion, string extraction, complex Pascal data structures.


Balancing a chemical equation

If you like this program, please, support me and this website by signing my guestbook.