Home -> Programming -> Processing -> Logic

Logic

Logical Comparisons

When programming computers we often use the boolean data type. When we compare two literals, variables or constants, the result is a boolean outcome: True or False. There are several different comparisons that can be made. The general expression for these comparisons is:

A op B

They specific comparisons are:
In every case the result is either the value True, or the value False. These comparisons are the basis of all conditional programming. A simple comparison looks like this:

If A = B then
      'clause which executes when the comparison is True
[Else
      'clause which executes when the comparison is False]
EndIf

The part inside the square brackets is optional. A conditional has no Else statement. a forced choice does. We can test many things with simple comparisons, but sometimes we need to make two or more comparisons. This is where our logic tables come in.

Logic Tables

For a test or two items we must do two or more comparisons. It should look like this:

If (A = B op C = D) then
      'clause which executes when the comparison is True
[Else
      'clause which executes when the comparison is False]
EndIf

There are two multiple comparison logical operators. They are:

Logic tables tell us what the results will be for each of the different type of comparisons.

And Logic Table Comparison 1
True False
Comparison 2 True True False
False False False
Or Logic Table Comparison 1
True False
Comparison 2 True True True
False True False

For the And table both comparisons must have the value of True for the combined result to be True. For the Or Table the only way for the combined result to be False is if both comparisons are False.

The third Truth Table is the Not table. It performs a logical inversion on all comparisons it is applied to. In plain english it turns True into False and False into True. This is very handy in many situations because it allows us to manipulate which set of statements will be in the then clause and which set of statements will appear in the Else clause. Here is the table:

Not Logic Table True False
True False False
False True False



For example if we want to check a control to see if its contents can be converted to a number we could use the IsNumeric function. Normally one would set the code up like this:

If IsNumeric(txtNumber.Text) then
    'put your calculation code here
Else
      'put message box code here
EndIf

However if we are error trapping, we want the calculation in the Else clause (see the next section). By using the Not operator we can swap the position of the clauses. Now the user message is in the Then clause and the calculation is in the Else clause:

If Not IsNumeric(txtNumber.Text) then
     'put message box code here
Else
     'put your calculation code here
EndIf