Learning to program (viii) – strings and functions

Now that we have briefly looked at strings, we can improve upon the function readNum(), defined previously. Remember that it only had one line of code inside it, which didn’t make it that useful. Now consider this snippet of code:

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

What about if we combined these two lines of code into one? So somehow integrate the print statement into the function readNum(). This can be achieved by passing the phrase “How many trees? “, to the function readNum(). So readNum() would be activated in the following manner:

n = readNum("How many trees? ")

The function itself now looks like this:

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

It takes str as input, and gives it to print, which prints it out. The other two lines are the same as before. This reduces the size of the overall program.

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

n = readNum("How many trees? ")

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
   c = readNum("Enter the circumference of the tree (inches): ")

   println("Tree Species: ")
   for i=1:length(species)
      println("(",i,") ",species[i])
   end
   t = readNum("Choose a tree (?): ")

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

end

 

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