 Introduction to Conditions

Logical Operators

Introduction

 Logical comparisons make it possible to find out if two values are the same, if they are different, if one is greater or smaller than the other, etc. A comparison can be performed on two variables, in which case their values would be tested. The comparison can be performed on a variable and a constant value. In both cases, the variable(s) and the value must be of the same type or they must be compatible.

The True and False Constants

Boolean algebra uses two constants to indicate its values. If a comparison is valid, it produces a value as True. If not, it produces a value of False.

Built-in Logical Constants: NULL

A variable is said to be null when its value is invalid or doesn't bear any significant or recognizable value. To assist you to represent such a value, the Visual Basic language provides the NULL keyword.

Equality =

To compare two variables for equality, use the = operator. The formula to follow is:

`value1 = value2`

The equality operation is used to find out whether two variables (or one variable and a constant) hold the same value. The comparison can be illustrated follows: Not Equal <>

To let you find out if two variables, or a variable and a constant, are not equal, the Visual Basic language provides the <> operator. Its formula is:

`value1 <> value2`

The comparison can be illustrated as follows: A Lower Value <

To find out whether one value is lower than another, use the < operator. The formula to follow is:

`value1 < value2`

If the value held by the left operand is lower than that of the right operand, the comparison produces a True result. The comparison can be resumed as follows: Less Than Or Equal: <=

To combine the comparison for equality and lower value, you can use the <= operator. The formula to follow is:

`value1 <= value2`

If both operands hold the same value, or the left operand is lower than the right operand, the result is true. Otherwise it is false. This can be illustrated as follows: Greater Value >

To find out whether one value is greater that another, use the > symbol. Its formula is:

`value1 > value2`

The comparison can follow a logic as follows: Greater or Equal Value >=

The greater than and the equality operators can be combined to produce an operator as follows: >=. This is the "greater than or equal to" operator. It uses the following formula:

`value1 >= value2`

The comparison can be illustrated as follows: Fundamentals of Boolean Values

The Boolean Data Type

A value is referred to as Boolean if it can be either true or false. Like a number or a string, a Boolean value can be stored in a variable. To declare such a variable, use the Boolean data type. Here is an example:

```Private Sub cmdCondition_Click()
Dim drinkingUnderAge As Boolean
End Sub```

Initializing a Boolean Variable

To use a Boolean variable, you can assign a value to it. By default, if you declare a Boolean variable but do not initialized it, it receives a value of False. Otherwise, to initialize a Boolean variable, assign it a True or a False value. Here is an example:

```Private Sub cmdCondition_Click()
Dim drinkingUnderAge As Boolean

drinkingUnderAge = True

MsgBox drinkingUnderAge, vbOKOnly Or vbInformation, "Drinking Test"
End Sub```

A Boolean variable can also be initialized with a Boolean expression. Here is an example:

```Private Sub cmdCondition_Click()
Dim age As Integer
Dim drinkingUnderAge As Boolean

age = 21

drinkingUnderAge = age >= 21
End Sub```

In this case, it is a good idea to put the Boolean expression in parentheses. Here is an example:

```Private Sub cmdCondition_Click()
Dim age As Integer
Dim drinkingUnderAge As Boolean

age = 21

drinkingUnderAge = (age >= 21)
End Sub```

At any time and when you judge it necessary, you can change the value of the Boolean variable by assigning it a True or False value.

Boolean Conversion

To let you convert a value to Boolean, the Visual Basic language provides a function named CBool. Its syntax is:

`Function CBool(ByVal Expression As Variant) As Boolean`

Like all conversion functions, CBool takes one argument, the expression to be evaluated. The function returns True or False.

On the other hand, to convert a Boolean value to a string, call the CStr() function. Here is an example:

```Private Sub cmdCondition_Click()
Dim drinkingUnderAge As Boolean

drinkingUnderAge = True

MsgBox "Result of drinking test: " & CStr(drinkingUnderAge), _
vbOKOnly Or vbInformation, "Drinking Test"
End Sub```

A Boolean Value as a Number

In the Visual Basic language, a Boolean variable can also deal with numeric values. The False value is equivalent to 0. For example, instead of False, you can initialize a Boolean variable with 0. Any other numeric value, whether positive or negative, corresponds to True. Consider the followin example:

```Private Sub cmdCondition_Click()
Dim employeeIsMarried As Boolean

employeeIsMarried = 13708

MsgBox "Employee Is Married? " & employeeIsMarried, _
vbOKOnly Or vbInformation, "Employment Application"
End Sub```

The number can be decimal or hexadecimal:

Boolean as a Data Type

Passing a Boolean Value as Argument

A Boolean value can be passed to a procedure and/or a function can be made to return a Boolean value. To pass an argument as a Boolean value, in the parentheses of the procedure, type the name of the argument followed by the As Boolean expression. Here is an example:

```Private Sub CheckingEmployee(ByVal IsFullTime As Boolean)

End Sub```

In the same way, you can create a procedure or function with as many Boolean parameters as you need, and you can combine Boolean and non-Boolean parameters as you judge necessary. Then, in the body of the procedure, use or don't use the Boolean parameter(s).

Returning a Boolean Value

Just as done for the other data types, you can create a function that returns a Boolean value. When declaring the function, specify its name and t he As Boolean expression on the right side of the closing parenthesis. Here is an example:

```Public Function IsDifferent() As Boolean

End Function;```

Of course, the function can take arguments of any kind you judge necessary

In the body of the function, do whatever you judge necessary. Before exiting the function, you must return a value that evaluates to True or False.

A Boolean Member in a Class

A member variable of a class can be a Boolean type. Here is an example:

Class Module: House

```public Bathrooms As Single
public HasCarGarage As Boolean
public MarketValue As Decimal```

If a Statement is True, Then...

Introduction

The comparison operators we have reviewed above are used to know the state of two variables but they don't provide a mechanism to exploit the result. After getting the result of a comparison, to use it effectively, you can formulate a conditional statement. Microsoft Access and Microsoft Visual Basic support this through various keywords and functions.

The If...Then statement examines the truthfulness of an expression. Structurally, its formula is:

`If Condition Then Statement`

The program will examine the Condition. This condition can be a simple expression or a combination of expressions. If the Condition is true, then the program will execute the Statement. This can be illustrated as follows: There are two ways you can use the If...Then statement. If the conditional expression is short enough, you can write it on one line using the following formula:

`If Condition Then Statement`

In the following example, if the text box named txtGender of a form displays Male, the background color of the Detail section would be colored in light blue:

```Private Sub Command0_Click()
Dim dNumber As Double

dNumber = CDbl(txtNumber)

If dNumber > 22 Then MsgBox "The number is greater than 22"
End Sub``` Practical Learning: Introducing Conditional Statements

1. Start Microsoft Access
2. From the list of files, click Business Mathematics
3. In the Navigation Pane, right-click Bill Preparation1 and click Design View
4. On the form, right-click the Calculate button and click Build Event...
5. In the Choose Builder dialog box, double-click Code Builder
6. Implement the event as follows:
```Private Sub cmdCalculate_Click()
Dim pricePerCCF As Double
Dim monthlyCharges As Double
Dim consumption As Double

pricePerCCF = 50#
monthlyCharges = 0#
consumption = CDbl(txtConsumption)

If consumption >= 0.5 Then pricePerCCF = 35#

txtPricePerCCF = pricePerCCF

pricePerCCF = CDbl(txtPricePerCCF)

monthlyCharges = consumption * pricePerCCF

txtMonthlyCharges = Format(monthlyCharges, "Fixed")
End Sub```
7. Return to Microsoft Accecss and switch the form to Form View 8. Click Consumption and type 0.48 and click the button: 9. Click Consumption and type 1.39 and Press Enter 10. Save and close the form

Ending a Conditional Statement

If there are many statements to execute as a truthful result of the condition, you should write the statements on subsequent lines. Of course, you can use this technique even if the condition you are examining is short. If then you use the Statement on a different line, you must terminate the conditional statement with the End If expression. The formula used is:

```If Condition Then
Statement
End If```

The example above can be re-written as follows:

```Private Sub Command0_Click()
Dim dNumber As Double

dNumber = CDbl(txtNumber)

If dNumber > 22 Then
MsgBox "The number is greater than 22"
End If
End Sub```

A Multi-Line Conditional Statement

If the condition needs to cover many lines of code, the syntax to apply is:

```If Condition Then
Statement1
Statement2
Statement_n
End If```

Here is an example:

```Private Sub cmdCheck_Click()
Dim dAge As Double

dAge = CDbl(txtAge)

If dAge >= 21 Then
MsgBox "The number is greater than 22."
MsgBox "The member will be considered an adult."
End If
End Sub```

If a Condition is False

Something Else

To address an alternative to an If...Then expression, you can use the Else condition. The formula to follow is:

```If condition Then
statement1
Else
statement2
End If```

If the condition produces a True result, then statement1 would execute. If the condition is false, statement2 would execute. Practical Learning: Conditionally Stating an Else Statement

1. From the resources that accompany these lessons, open the Geometry1 database
2. In the Navigation Pane, right-click Uniform Quadrilateral and click Design View
3. In the Controls section of the Ribbon, click Image and click the form
4. From the resources that accompany these lessons, select and open Square1
5. On the form, right-click the Calculate button and click Code Builder
6. In the Choose Builder dialog, double-click Code Builder and implement the event as follows:
```Private Sub cmdCalculate_Click()
Dim side As Double
Dim perimeter As Double
Dim area As Double

If txtSide = "" Then
side = 0#
Else
side = CDbl(txtSide)
End If

perimeter = side * 4
area = side * side

txtPerimeter = CStr(perimeter)
txtArea = CStr(area)
End Sub```
7. Return to Microsoft Access and switch the form to Form View 8. Click Side and type a number such as 107.69 and click the Calculate button 9. Save and close the form

What Else If a Condition is True?

An If...Then...Else conditional statement can process only two statements. If you need to process more conditions, you can add an ElseIf condition. The formula to follow is:

```If Condition1 Then
statement1
ElseIf condition2 Then
statement2
End If```

The first condition, condition1, would be checked. If condition1 is true, then statement1 would execute. If condition1 is false, then condition2 would be checked. If condition2 is true, then statement2 would execute. Any other result would be ignored.

If you need to process more than two conditions, you can add more ElseIf sections. The formula to follow would be:

```If condition1 Then
statement1
ElseIf condition2 Then
statement2
ElseIf condition3 Then
Statement3
. . .
ElseIf condition-n Then
Statement-n
End If``` Practical Learning: Handling Many Statements

1. From the resources that accompany these lessons, open the Chemistry1 database
2. In the Navigation Pane, right-click Compound Properties and click Design View
3. On the form, right-click the Find button and click Build Event
4. In the Choose Builder dialog, click Code Builder and click OK
5. Implement the event as follows:
```Private Sub cmdFind_Click()
Dim chemicalSymbol As String
Dim atomicNumber As Integer
Dim elementName As String
Dim atomicMass As Single

If txtChemicalSymbol = "" Then
chemicalSymbol = "H"
Else
chemicalSymbol = txtChemicalSymbol
End If

If chemicalSymbol = "H" Then
atomicNumber = 1
elementName = "Hydrogen"
atomicMass = 1.0079
ElseIf chemicalSymbol = "He" Then
atomicNumber = 2
elementName = "Helium"
atomicMass = 4.002682
ElseIf chemicalSymbol = "Li" Then
atomicNumber = 3
elementName = "Lithium"
atomicMass = 6.941
ElseIf chemicalSymbol = "Be" Then
atomicNumber = 4
elementName = "Berylium"
atomicMass = 9.0122
ElseIf chemicalSymbol = "B" Then
atomicNumber = 5
elementName = "Boron"
atomicMass = 10.811
End If

txtAtomicNumber = CStr(atomicNumber)
txtElementName = CStr(elementName)
txtAtomicMass = CStr(atomicMass)
End Sub
```
6. Return to Microsoft Access and switch the form to Form View 7. Click Chemical Symbol and type a chemistry element such as Be and click the Find button Whatever Else?

If none of the conditions matches, you can add a last Else condition. The formulas to follow are:

```If condition1 Then
statement1
ElseIf condition2 Then
statement2
Else
else-statement
End If```

or

```If condition1 Then
statement1
ElseIf condition2 Then
statement2
ElseIf condition3 Then
Statement3
. . .
ElseIf condition-n Then
Statement-n
Else
else-statement
End If``` Practical Learning: Using Whatever Else

1. Change the statement as follows:
```Private Sub cmdFind_Click()
Dim chemicalSymbol As String
Dim atomicNumber As Integer
Dim elementName As String
Dim atomicMass As Single

If txtChemicalSymbol <> "" Then
chemicalSymbol = txtChemicalSymbol
End If

If chemicalSymbol = "H" Then
atomicNumber = 1
elementName = "Hydrogen"
atomicMass = 1.0079
ElseIf chemicalSymbol = "He" Then
atomicNumber = 2
elementName = "Helium"
atomicMass = 4.002682
ElseIf chemicalSymbol = "Li" Then
atomicNumber = 3
elementName = "Lithium"
atomicMass = 6.941
ElseIf chemicalSymbol = "Be" Then
atomicNumber = 4
elementName = "Berylium"
atomicMass = 9.0122
ElseIf chemicalSymbol = "B" Then
atomicNumber = 5
elementName = "Boron"
atomicMass = 10.811
Else
atomicNumber = 0
elementName = "Unknown"
atomicMass = 0#
End If

txtAtomicNumber = CStr(atomicNumber)
txtElementName = CStr(elementName)
txtAtomicMass = CStr(atomicMass)
End Sub
```
3. Click Chemical Symbol and press Delete 4. Click the Find button Accessories for Conditional Statements

Going To a Label

The Goto statement allows a program execution to jump to another section of a procedure in which it is being used. In order to use the Goto statement, insert a name on a particular section of your procedure so you can refer to that name. The name, also called a label, is made of one word and follows the rules we have applied to names (the name can be anything), then followed by a colon ":". Here is an example:

```Private Sub cmdCondition_Click()

' Do some thing(s) here

SomeLabelHere:
' Do some other thing(s) here
End Sub```

After creating the label, in the code before the label, you can do something. In that section, if a condition happens that calls for jumping to the label, then use a GoTo statement to send the flow to the corresponding label by typing the name of the label on the right side of GoTo. Here is an example:

```Private Sub cmdCondition_Click()
Dim Number%

Rem Request a number from the user
Number% = InputBox("Enter a number that is lower than 5")

Rem Find if the number is positive or 0
If Number% < 0 Then
GoTo NegativeNumber
Else
Rem If the number is positive, display it
MsgBox Number%
End If

NegativeNumber:
MsgBox "You entered a negative number"
End Sub```

In the same way, you can create as many labels as you judge them necessary in your code and refer to them when you want. The name must be unique in its scope. This means that each label must have a unique name in the same procedure. Here is an example with various labels:

```Private Sub cmdCondition_Click()

Answer = InputBox(" -=- Multiple Choice Question -=-" & vbCrLf & _
"To create a constant in your code, " & _
"you can use the Constant keyword" & vbCrLf & _

If Answer = 1 Then GoTo Wrong
If Answer = 2 Then GoTo Right

Wrong:
MsgBox"Wrong: The keyword used to create a constant is Const"
GoTo Leaving

Right:  MsgBox"Right: Constant is not a keyword"

Leaving:

End Sub```

Here is an example of executing the program with Answer = 1:  Here is another example of executing the same program with Answer = 2:  Negating a Conditional Statement

As you should be aware by now, Boolean algebra stands by two values, True and False, that are opposite each other. In fact, the Visual Basic language provides an operator that can be used to reverse a Boolean value or to negate a Boolean expression. This is the role of the Not operator. The formula to use it is:

`Not Expression`

To use the operator, type Not followed by a logical expression. The expression can be a simple Boolean value. Here is an example:

```Private Sub cmdCreate_Click()
Dim IsMarried As Boolean

MsgBox "Employee is married: " & IsMarried, _
vbOKOnly Or vbInformation, "Employment Application"
MsgBox "Employee is married: " & Not IsMarried, _
vbOKOnly Or vbInformation, "Employment Application"
End Sub```

This would produce:  In this case, the Not operator is used to change the logical value of the variable. When a Boolean variable has been "notted", its logical value has changed. If the logical value was True, it would be changed to False and vice versa. Therefore, you can inverse the logical value of a Boolean variable by "notting" or not "notting" it. Practical Learning: Negating a Conditional Statement

1. Change the statement as follows:
```Private Sub cmdFind_Click()
Dim chemicalSymbol As String
Dim atomicNumber As Integer
Dim elementName As String
Dim atomicMass As Single

If Not (txtChemicalSymbol = "") Then
chemicalSymbol = txtChemicalSymbol
End If

If chemicalSymbol = "H" Then
atomicNumber = 1
elementName = "Hydrogen"
atomicMass = 1.0079
ElseIf chemicalSymbol = "He" Then
atomicNumber = 2
elementName = "Helium"
atomicMass = 4.002682
ElseIf chemicalSymbol = "Li" Then
atomicNumber = 3
elementName = "Lithium"
atomicMass = 6.941
ElseIf chemicalSymbol = "Be" Then
atomicNumber = 4
elementName = "Berylium"
atomicMass = 9.0122
ElseIf chemicalSymbol = "B" Then
atomicNumber = 5
elementName = "Boron"
atomicMass = 10.811
Else
atomicNumber = 0
elementName = "Unknown"
atomicMass = 0#
End If

txtAtomicNumber = CStr(atomicNumber)
txtElementName = CStr(elementName)
txtAtomicMass = CStr(atomicMass)
End Sub```  