Arrays (Chapter 5) Definition Applications One-Dimensional –Declaration –Initialization –Use Multidimensional
Declaration #define SIZE 10 int main(void) { float sample[SIZE];
Initialization #define SIZE 10 int main(void) { float sample[SIZE] = {5.0, 1.2, -4.6, -7.5, 8.9, -1.0, 12.7, 0.0, 6.6, 4.2};
Gotchas First element of array is [0] Last element of array is [n-1] (major source of bugs!) No bounds check (MAJOR source of impossible-to- find bugs!)
Amino Acids I like this problem, but I don't especially like the way the book does it. The book isn't careful enough about range errors. We can use a table-driven approach to looking up the atomic weights of the elements. This takes more space (bad), less time (good) than the way the book looks up the weights. Also less opportunity for bugs (very, very good).
Background Amino Acid: Organic molecule composed of carbon, hydrogen, nitrogen, oxygen, sulfur. Building blocks of proteins. Amino acids are what DNA codes for. Weight is sum of weights of component atoms
Syntax One amino acid formula on a single line Amino acid formula consists of sequence of atom counts Atom count is a letter specifying the atom, maybe followed by a number specifying how many of them. O2C3NH7\n
Semantics O2C3NH7\n –Two Oxygen (2.0 * = )
Semantics O2C3NH7\n –Two Oxygen (2.0 * = ) –Three Carbon (3.0 * = )
Semantics O2C3NH7\n –Two Oxygen (2.0 * = ) –Three Carbon (3.0 * = ) –One Nitrogen ( )
Semantics O2C3NH7\n –Two Oxygen (2.0 * = ) –Three Carbon (3.0 * = ) –One Nitrogen ( ) –Seven Hydrogen (7.0 * = )
Semantics O2C3NH7\n –Two Oxygen (2.0 * = ) –Three Carbon (3.0 * = ) –One Nitrogen ( ) –Seven Hydrogen (7.0 * = ) Total: =
Parsing O2C3NH7\n Find new atoms (letters)
Parsing O2C3NH7\n Find new atoms (letters) –Look up atomic weight of atom (12.011)
Parsing O2C3NH7\n Find new atoms (letters) –Look up atomic weight of atom (12.011) Count how many we've got (numbers)
Parsing O2C3NH7\n Find new atoms (letters) –Look up atomic weight of atom (12.011) Count how many we've got (numbers) –3
Parsing O2C3NH7\n Find new atoms (letters) –Look up atomic weight of atom (12.011) Count how many we've got (numbers) –3 When we reach next atom, add previous to atomic weight of molecule
Parsing O2C3NH7\n Find new atoms (letters) –Look up atomic weight of atom (12.011) Count how many we've got (numbers) –3 When we reach next atom, add previous to atomic weight of molecule –3* =
Look Up Atomic Weight
Counting numatoms = numatoms * newdigit;
Counting numatoms = numatoms * newdigit; 123
Counting numatoms = numatoms * newdigit; 123 0* = 1
Counting numatoms = numatoms * newdigit; 123 1* = 12
Counting numatoms = numatoms * newdigit; * = 123
Special Cases First letter: make sure we don't put gibberish in molecular weight End of string: make sure we account for last atom If user didn't enter number for an atom, it means '1'
Writing the code Write initialization, input, core loop, output Handle special cases Error checking