Learning to program (vii) – strings

In the same way that we put all the growth factors into an array, we can do the same with the tree species.

species = ["Silver Maple", "White Birch", "Black Walnut", 
           "Red Oak", "White Oak", "American Elm"]

Now we can use this to “shrink” the program code for the menu.

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

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

species = ["Silver Maple", "White Birch", "Black Walnut",
           "Red Oak", "White Oak", "American Elm"]
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: ")
   for i=1:length(species)
      println("(",i,") ",species[i])
   end
   print("Choose a tree (?): ")
   t = readNum()

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

end

It is also possible to modify the code in the final println in order to specify the type of tree selected by the user. Here’s what the program looks like when it runs:

How many trees? 2
Enter the circumference of the tree (inches): 97
Tree Species:
(1) Silver Maple
(2) White Birch
(3) Black Walnut
(4) Red Oak
(5) White Oak
(6) American Elm
Choose a tree (?): 1
The American Elm is 92.63 years old
Enter the circumference of the tree (inches): 40
Tree Species:
(1) Silver Maple
(2) White Birch
(3) Black Walnut
(4) Red Oak
(5) White Oak
(6) American Elm
Choose a tree (?): 6
The American Elm is 50.93 years old

 

 

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s