Learning to program (iv) – going loopy in Julia

Our program as it stands works quite well. Here it is again:

println("Enter the circumference of the tree (inches): ")
c = parse(chomp(readline()))

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 = parse(chomp(readline()))

if (t == 1)
   g = 3.0
elseif (t == 2)
   g = 5.0
elseif (t == 3)
   g = 4.5
elseif (t == 4)
   g = 4.0
elseif (t == 5)
   g = 5.0
elseif (t == 6)
   g = 4.0
end

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

But it only works once. What if we wanted to calculate the age of a series of trees? This would require some form of repetition. Say we let the user enter the number of trees whose age they want to calculate:

print("How many trees? ")
n = parse(chomp(readline()))

Then we can use the value of n to repeat the whole process n times. This may be done using a for loop:

for i=1:n
   # something
end

The something is replaced by the whole of the program from the previous post. So now the program looks like this:

print("How many trees? ")
n = parse(chomp(readline()))

for i=1:n

   println("Enter the circumference of the tree (inches): ")
   c = parse(chomp(readline()))

   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 = parse(chomp(readline()))

   if (t == 1)
      g = 3.0
   elseif (t == 2)
      g = 5.0
   elseif (t == 3)
      g = 4.5
   elseif (t == 4)
      g = 4.0
   elseif (t == 5)
      g = 5.0
   elseif (t == 6)
      g = 4.0
   end

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

end

Now the user can specify how many trees they want to calculate the age of, and the program will run accordingly.

 

 

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