Anda di halaman 1dari 7

Lesson IV.

Logical Structures

Objectives
To able to write simple decision-making statements
To be able to use the If-Then and If-Then-Else selection structures to choose between
alternative actions
To use Logical Operators
To use the Format() function

Notes
Logical structures allow nesting in the program flow. You might want to do a particular routine if a
certain condition is true, and do another routine if it isnt. For example, if you want to check if a
student has passed a subject, what do you do? You check if his grade is greater than or equal to
the passing grade. You say Passed if this is true. Otherwise, you say Failed.
There are a couple of logical structures in VB. What we will discuss in this lesson are: If, If-Else,
and the Select-Case statements. But before going into these, let us discuss Comparison and
Logical Operators first.
IN FOCUS: COMPARISON AND LOGICAL OPERATORS
Comparison operators compare data values against each other and produce True or False results.
Put simply, we evaluate a comparison expression as True or False. The expression 1>2 is false
because 1 is not greater than 2. The following table describes the comparison operators provided
for by Visual Basic.
Operator
>

Usage
Salary > 10,000

<

Age < 18

Gender =
Female

>=

Grade >= 60

<=

Total <= Quota

<>

Course <> CS

Description
Returns true of if the value on the left
hand side is greater than the value on the
right hand side.
Returns true of if the value on the left
hand side is less than the value on the
right hand side.
Returns true of if the values on the left
and right hand sides are equal to each
other.
Returns true of if the value on the left
hand side is greater than or equal to the
value on the right hand side.
Returns true of if the value on the left
hand side is less than or equal to the
value on the right hand side.
Returns true of if the values on the left
and right hand sides are unequal.

Note that expressions on both sides of a comparison operator should conform to the same data
type or at least compatible types. You cannot compare String and numeric values, as this will cause
a type mismatch error.
VB also supports three additional operators And, Or, and Not. These are called Logical
Operators. Logical operators allow you to combine two or more comparison tests into a single
compound comparison expression.
The next table describes the logical operators.
Operator
And
Or

Usage
(A>B) And (C<D)
(A>B) Or (C<D)

Not

Not (A>B)

Description
Returns true if both expressions are true.
Returns true if at least one expression is
true.
Returns true if the expression (A>B) is
false. It returns false if the expression is
true.

Comparisons are evaluated from left to right unless explicitly indicated by parentheses. Consider
the following expressions:
Expression 1.
Expression 2.

(1>3) Or (2=2) And (3<=2)


(1>3) Or ((2=2) And (3<=2))

False Or True And False

False Or (True And False)

The expression 1 returns False while expression 2 returns True. Expression 1 is evaluated from left
to right, evaluating the Or expression first then the And. In expression 2, the And expression is
evaluated first because it is enclosed in parentheses.
IN FOCUS: IF STATEMENT
The If statement has the following syntax:
If <comparisonExpression> Then
One or more VB statements
End If

Comp
Exp
F

VB Statement/s

Flowchart of If-Then structure

The statements enclosed in the If statement are executed only if <comparisonExpression> is true.
In the following example, the allowance is increased by 50 only if the grade is greater than 90.
If (Grade>90) Then
allowance = allowance + 50
End If
IN FOCUS: IF-ELSE STATEMENT
If-Else statement is an extension of the If statement. While nesting in an If statement is this way
or nowhere, If-Else is this way or that way. The syntax is as follows:
If <comparisonExpression> Then
One or more VB statements
Else
One or more VB statements
End If

CompE
xp

VB Statement/s

F
VB Statement/s

Flowchart of If-Then-Else structure

As in the If statement, if <comparisonExpression> is true, the statement block proceeding Then is


executed. The If-Else statement executes the statements after the Else keyword if this is false. The
following is an example:
If (grade>=60) Then
lblOutput.Caption = You passed!
Else
lblOutput.Caption = Sorry but you failed.
End If
IN FOCUS: SELECT CASE STATEMENT
If we are comparing an expression to several expressions, the If-Else statement may not be
efficient. Consider this example: display Excellent if the grade falls within the range 86-100,
Outstanding for grades 71-85, Good for grades 50-70, and Failed for grades below 50. This
can be done through If-Else statement:

If (grade>=86) Then
lblOutput.Caption = Excellent
Else
If (grade>=71) Then
lblOutput.Caption = Outstanding
Else
If (grade>=50) Then
LblOutput.Caption = Good
Else
LblOutoput.Caption = Failed
End If
End If
End If
The above code works but the coding is extremely difficult to follow.
Visual Basic supports another logical statement called Select Case. The syntax is as follows:
Select Case <expression>
Case <value>:
One or More VB statements
Case <value>:
One or More VB statements

Case <value>:
One or More VB statements
Case Else
One or More VB statements
End Select
<expression> can be any VB expression such as a calculation, a string value, or a numeric value
provided that it results in an integer or a string value. Each <value> must be compatible with
<expression>, that is, if <expression> results in an integer, then all <value>s must be integers as
well. VB compares <expression> to each <value>. If it finds a match, it executes the statements
that immediately follow it. It then ignores the rest of the Case statements. In the event when no
matches have been found, then the statements following the Case Else are executed.

T
CompExp 1

VB Statement/s

F
T
CompExp 2

VB Statement/s

F
T
CompExp N

VB Statement/s

VB Statement/s

Flowchart of Select-Case structure

The Case clause has several variations. Case <value> works when you are comparing
<expression> to several specific values (e.g. Case 6, Case Computer). If you want to compare it
to a range of values, you use either:

Case Is <relation>:
e.g. Case Is <5:
or
Case <expression1> To <expression2>:
e.g. Case 40 To 60:
The following code is the translation of the If-Else code to Select-Case. It is now shorter and more
readable.
Select Case grade
Case 50 To 70:
lblOutput.Caption = Good
Case 71 To 85:
lblOutput.Caption = Outstanding
Case 86 To 100: lblOutput.Caption = Excellent
Case Else:
lblOutput.Caption = Failed
End Select
IN FOCUS: FORMAT FUNCTION
The Format() function enables you to format how data are displayed. If variable total_cost
contains the total amount of a product, you might want to display the value of this variable in
currency format (in 2 decimal places with a currency sign).
Format() does not change a value, it only changes the way a value looks. This function returns a
variant. The following is Format()s syntax:
Format(<expression>, <strFormat>)
<expression> can be any variable, expression, or a constant. <strFormat> may be a value in the
following table:

strFormat

Description

Currency

A dollar sign appears before the formatted value. The


value has a comma thousands separator and 2 decimal
places. Negative values are automatically enclosed in
parentheses.

Fixed

Displays at least one digit before and two digits following


the decimal point, with no thousands separator.

General
Number

Displays the number with no thousands separator.

Percent

Displays the number, multiplied by 100, and adds


appends percent sign to the right of the number.

You can also create your own strFormat. Youll just need a combination of pound sign and zeros to
format values. Each pound sign indicates where a significant digit goes. The zero indicates that you
want either leading or trailing zeros, whether the zero or significant or not.
Examples:
A = 123.3232
B = 23.0002
C = 12233
D = .34
Format Expression
Format(A, Currency)
Format(D, Percent)
Format(B, Fixed)
Format(D, ###)
Format(D, ##.###)
Format(D,0.000)
Format(C,#,###.00)
Format(C,#,###.##)
Format(C, P #,##0.00)

Result
$ 123.32
34%
23.00
Nothing
.34
0.340
12,233.00
12,233.
P 12, 233.00

Lesson in Action
We will create an application that asks for two grades and
outputs their average. It will then display Passed if the
average is greater than or equal to 60 or Failed if the
average grade is less than 60.

1. Create a new project.


2. For the Form control, set the following properties:
Name
frmMain
Caption
Grading Program
BorderStyle
1 Fixed Single
StartUpPosition
Center Screen
Height
5145
Width
5325
BackColor
White
3.

Drag 2 Labels to the Form:


Set the following properties for the first Label:

Name
lblMGrade

BackStyle
Transparent

Caption
Enter your Midterm Grade:

Font
Arial, Size 16

Top
240

Left
240
Set the following properties for the second Label:

Name
lblFGrade

BackStyle
Transparent

Caption
Enter your Final Grade:

Font
Arial, Size 16

Top
960

Left
240

4.

Drag 2 TextBoxes to the Form.


Set the following Properties for the first TextBox:

Name
txtMGrade

Font
Arial, Size 14

Text
(None. Erase Default Value)

Width
615

Height
495

Top
240

Left
4200

MaxLength
3
Set the following properties for the second TextBox:

Name
txtFGrade

Font
Arial, Size 14

Text
(None. Erase Default Value)

Width
615

Height
495

Top
960

Left
4200

MaxLength
3

5.

Drag a Shape to the Form.


Set the following properties for the Shape:

Name
shpRect

Width
4695

Height
1575

6.

Top
Left

1920
240

Drag 2 Labels to the Form.


Set the following properties for the first Label:

Name
lblAve

Font
Arial, Size 14

Caption
Average:

Width
2175

Height
375

BackColor
Light Yellow

Top
2160

Left
840

Set the following properties for the second Label:

Name
lblRema

Font
Arial, Size 14

Caption
Remark:

Width
2175

Height
375

BackColor
Light Yellow

Top
2760

Left
840
7. Drag additional 2 Labels to the Form.
Set the following properties for Label 1:

Name
lblAverage

Caption
None. Erase Default Value

Width
1215

Height
375

Top
2160

Left
3120

Backcolor
Lightyellow
Set the following properties for Label 2:

Name
lblRemark

Caption
None. Erase Default Value

Width
1215

Height
375

Top
2760

Left
3120

Backcolor
Lightyellow
8.

Drag a CommandButton to the Form.


Set the following properties for the CommandButton.

Name
cmdCompute

Caption
COMPUTE

Width
1455

Height
495

Top
3960

Left
1800

9.
Double Click on the Command
cmdCompute_Click procedure.

Button.

Enter

the

Private Sub cmdCompute_Click()


a = (Val(txtMGrade.Text) + Val(txtFGrade.Text)) / 2
lblAverage.Caption = Format(a, "##0")
If (a >= 60) Then
lblRemark.Caption = "Passed"
Else
lblRemark.Caption = "Failed"
End If
End Sub
10.

Run the application and see how your new application works.

following

code

to

your

11.

Save your work as Lesson4.vbp.

On your Own
1.

Rewrite the following nested If statement using a single If with a logical operator:
If (level >= 2) Then
If (course = BSCE) Then
lblResult.Caption = Qualified Member
End If
End If

2.

How do comparison operators differ from mathematical operators?

3.

What role does the ASCII table play in comparison logic?

4.

What happens if every Case fails and there is no Case Else option?

5.

Rewrite the following If statement to eliminate the Not. The logic should still be the same.
If Not(A < 4) Or Not(college = Engineering) Then

6. Write a program that contains a TextBox and a CommandButton. Put a Label above the
TextBox that tells the user to type a number from 1 to 10 inside the TextBox. Display a default
value of 0. When the user clicks the CommandButton, check the TextBox for a valid number.
Display Valid Number in another Label if the number is within the range. Display Invalid
Number. Please enter a number from 1 to 10 when the entered value is out of range.

Anda mungkin juga menyukai