Learning to program (vi) – arrays

So this is a little bit more challenging. Our program works fine, however the if statement which selects the value of the tree is somewhat large. If you had 200 trees to choose from, it would be kinda messy. Is there a better way? Yes, by storing the values of growth factor in an array. An array is just a container, which can hold more than one value. An array to hold the growth factors can be created in the following manner:

g = [3.0, 5.0, 4.5, 4.0, 5.0, 4.0]

Each of those values is an element in the array g. So the value of g[1] = 3.0, g[2] = 5.0, etc. Now we can modify the program to use this new container. Basically we can remove the entire if statement, and replace the single g in the equation, with the container g.

age = d * g[t]

Here the value of t entered by the user to specify the type of tree is used to access the appropriate element of g. This is what the whole program looks like now:

function readNum()
   c = parse(chomp(readline()))
   return c

print("How many trees? ")
n = readNum()

g = [3.0, 5.0, 4.5, 4.0, 5.0, 4.0]

for i=1:n

   print("Enter the circumference of the tree (inches): ")
   c = readNum()

   println("Tree Species: ")
   println("(1) Silver Maple")
   println("(2) White Birch")
   println("(3) Black Walnut")
   println("(4) Red Oak")
   println("(5) White Oak")
   println("(6) American Elm")
   print("Choose a tree (?): ")
   t = readNum()

   d = c / pi
   age = d * g[t]
   println("The tree is ", round(age,2), " years old")


As you can see, the program has shrunk considerably in size. Now adding 20 more trees is as simple as adding more values to the array g, and modifying the menu.



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s