Learning to program (iii) – an intermediary Julia program

Last time the Julia program we wrote worked on Silver Maples only. Now we will try and extend it to work with a series of different tree species. Here is the program as it stands.

println("Enter the circumference of the tree (inches): ") 
c = parse(chomp(readline())) 
d = c / pi 
g = 3.0 
age = d * g 
println("The tree is ", round(age,2), " years old")

Now to add more tree species requires the use of a sort of menu. Here is a piece of code to print a menu for the user to select an option from:

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()))

It basically prints out a table of six tree species, then prompts the user to enter the number which represents the menu item of the tree they want. The only thing missing is the growth factor associated with each tree? Now we need to use the number entered to assign a value to the variable “g“. This can be achieved using an if statement. The if statement is used in just about every language to make decisions. Basically we want to ask:

if the user inputs “1”, then the value of g is 3.0, because this is the growth factor for a Silver Maple.
if the user inputs “2”, then the value of g is 5.0, because this is the growth factor for a White Birch.
etc.

Here is the piece of code that does that:

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

Only one value of g will be assigned, depending on the value of t, which was the menu item selected by the user. Now let’s look at the whole program:

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")

Now the program is more functional, and technically, any number of tree species can be added to the if statement to expand its usability.

 

 

 

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