you must know the valency of your substituent elements. generally, group 1 exhibits valency 1+, group 2 valency 2+, group 3 valency 3+, group 4 valency 4+, group 5 valency 3-, group 6 valency 2-, group 7 valency -1. In order to decide the formula of your compound, you have to put them in such a way that the sum of valency is zero. eg. K is +1, Br is -1, so the compound must be KBr. for H is +1, oxygen is -2, then the compound is H2O, This is just the general rule for dealing with electrically neutral compound.