First the type of substance will need to be determined. There are essentially four types of compounds for which a formula may be written: 1) ionic compounds, 2) binary covalent compounds, 3) organic compounds, 4) acids. Each has its own order, but generally the least electronegative element is written first.
1) Ionic compounds are composed of a metal cation (a metal that has lost at least one electron to become charged) or the ammonium ion (NH4^+) bonded to a nonmetal anion or a polyatomic anion. In the case of all ionic compounds, the (metallic) cation is named first or written first in the formula. So in the case of NaCl, the Na is written first because it is the metallic cation.
2) Binary covalent compounds are composed of 2 nonmetals and the accepted practice is to name the element with the least electronegativity first. As a general rule, this element is furthest left on the Periodic Table. This is also true when writing the formula. So in the case of CO2, for example, the carbon is furthest left on the PT so it is first.
3) Organic compounds contain a hydrocarbon chain which may have additional elements, such as Oxygen, Sulfur, Nitrogen, Phosphorus, or a halogen bonded to it. Organic molecules start with Carbon, then hydrogen, and then any additional elements. An example of an organic compound is methane, CH4 or methanol, CH4O or CH3OH.
4) Acids are covalently bonded molecules that contain hydrogen that is ionized by water. They have a unique nomenclature system. There are two types of acids, inorganic and organic acids. Organic acids have the hydrocarbon structure with a -COOH group on the end. The order of elements in organic acids is C, H, then the -COOH group, for example ethanoic acid (aka acetic acid) is C2H4COOH. Inorganic acids do not contain Carbon (except H2CO3). In the case of inorganic acids, the H is first followed by the anion that would be formed when water ionizes the acid. An example of an inorganic acid would be HNO3.
Hope this helps!
Lets use the Hill system, carbon atoms are listed first, hydrogen atoms next, and then the number of all other elements in alphabetical order.
Short and sweet, hope it helps