Thursday, February 28, 2008

If Statements

We are covering If Statements this week. Let's see how if statements work:

If condition Then
'Do these statements
Else
'Do these alternate statements
End If


The condition is what we have to check, and if it is true then we do the statements that are immediately inside the If statement, otherwise we do what is in the Else statement. An English pseudocode example could be:

If It's sunny outside Then
'Go play frisbee outside
Else
'Stay inside and read
End If


Of course this is only an English example and will not make sense to the computer in this format.

Operators
Most often what we are trying to figure out has to do with relationships of things. For example, we had a calculator problem with a potential bug of division by 0. We could use If statements to decide If we are trying to divide by 0. In order to do this, we need to use some boolean operators. These operators allow us to figure out the relationship between two things, for example, is a number larger than another number, smaller than the other number or equal to it?

Our operators are:

= Equal to
<> Not Equal to
< Less Than
> Greater Than
<= Less Than or Equal to
>= Greater Than or Equal to


These operators compare the item on the left to the item on the right and return True if the relationship is true or False if the relationship is false. The items that we compare could be Numbers or Strings.

Therefore, if we want to see if a number is Equal to another number (in this case zero) we would use the equals operator. If num2 is equal to zero then we output an error message, otherwise we do the division (which is not shown here):

If num2 = 0 Then
MsgBox("Division by zero error!",,"ERROR")
Else
'Do Division
End If


Now we have a piece of code that we can use, or modify if we like. We could have used a different method by using the Not Equals Operator:

If num2 <> 0 Then
'Do Division
Else
MsgBox("Division by zero error!",,"ERROR")
End If


This says that if num2 is NOT equal to zero then do the division, otherwise output an error message.

Note: We do not have to have an Else with each If statement. We could just write:

If num2 <> 0 Then
'Do Division
End If


But nothing happens if a division by zero is attempted. The user might like to know why nothing happened, especially if they accidentally wrote 0 instead of another number like 10

In the next class we will go over this longer example.

No comments: