Lesson 5, Introduction to Control Structures
Part 3

We saw in the last lesson how we can we can handle more complex logic problems by nesting our If..then..Else decisions.  Although the answer in the last part was correct there's another way we can express that same logic that will make our coding a little more efficient and our logic model a little more complex.   As our problems get more and more complex you will find that this way of expressing your logic decisions a lot more flexible and understandable.

This was the way we flow charted the last problem:

<script language ="vbscript">
Option Explicit
Dim PetType, LivingLocation, Age, HumanYears

PetType = Inputbox("Cat or Dog?")
LivingLocation = Inputbox("Inside or Outside")
age = Inputbox("How many years has your pet been alive?")

'tests to see if the animal is a dog and where is lives
If PetType = "Dog" then
     If LivingLocation = "Inside" then
         Humanyears = Age * 6
     else
         Humanyears = Age * 7
     End If

Else
    If LivingLocation = "Inside" then
        Humanyears = Age * 7
    else
        Humanyears = Age * 8
    End If
End If
Document.write "your pet has lived " & humanyears
</script>

 

Instead of using a single comparison we can do more than one comparison and also use a slightly different structure.  We can call this If...ElseIf...Else to map out our answer.

Here's our new flowchart and code:

<script language ="vbscript">
Dim PetType, LivingLocation, Age, HumanYears

'takes in my three "Given" variables
PetType = Inputbox("Cat or Dog?")
LivingLocation = Inputbox("Inside or Outside")
age = Inputbox("How many years has your pet been alive?")

'tests to see if the animal is a dog and where is lives
If PetType = "Dog" And LivingLocation = "Inside" then
        Humanyears = Age * 6
elseIf PetType = "Dog" And LivingLocation = "Outside" then
         Humanyears = Age * 7

'this is what happens if it is not a "Dog"
elseIf PetType = "Cat" And LivingLocation = "Inside" then
        Humanyears = Age * 7
else
        Humanyears = Age * 8

End If
Document.write "your pet has lived " & humanyears
</script>

Yep, both codes and logic structures work perfectly, particularly for this fairly simple problem but as they get more complex you will find that the second way is more efficient to code and more understandable to flowchart.  When we use "If PetType = "Dog" and LivingLocation = "Inside" that means that both comparisons must be true for it to evaluate true.  If, instead, we had "If PetType = "Dog" OR LivingLocation = "Inside" then if either side of the comparison is true then it is evaluated as True.  Next we'll try another problem and see how this new way of making decisions makes our lives easier.