Chapter Objectives
At the end of the chapter, the student should be able to: understand how different program structure works; learn how to write algorithms using program structures; and evaluate algorithms which contain program structures.
2
DECISION/SELECTION STRUCTURES
If-Then Statements
A conditional statement used in directing program flow based on multiple decision criteria. It has an equivalent to the English form: “If such-and-such is true, then do so-and-so.” General forms: A. Single Selection 1. Single line If statement 2. If…Then B. Multiple Selection 3. If…Then…Else 4. Nested If…Then.. Else 5. If…Then…ElseIf
DECISION/SELECTION STRUCTURES
If-Then Statements
1. Single-Line Syntax: 2. If…Then…Syntax:
If [Condition] Then [Statement]
If [Condition] Then [Statements] End If
3. If...Then...Else Syntax:
If [Condition] Then [Statements] Else [Statements] End If
DECISION/SELECTION STRUCTURES
If-Then Statements
4. Nested If...Then...Else Syntax
Nesting is the process of embedding program statements in other statements
Below is the syntax for Nested If-Then Statements:
If [condition1] Then [VB statements] Else If [condition2] Then VB statements If [condition3] Then [VB statements] End If Else [VB Statements] End If End If
DECISION/SELECTION STRUCTURES
If-Then Statements
5. If-Then-ElseIf Syntax
The ElseIf keyword is used to specify several conditions in one If/Else Statement. Syntax:
If [condition1] Then [VB statements] ElseIf [condition2] Then [VB statements] ElseIf [condition3 Then [VB statements] End If
DECISION/SELECTION STRUCTURES
Assigning Condition in If-Then Statements
Below are condition statements that include conditional operators and results to a Boolean value (True or False):
IsNumeric(txtX.Text), Price >= 30000
If several conditions are to be used, logical operators are used to combine conditions into one larger condition:
IsNumeric(txtX.Text) And Price >= 30000
DECISION/SELECTION STRUCTURES
Example of If-Then Statements
Example 1: Determine the value that will be shown in output of the Console given the following code on the right. Note that the answer is False.
DECISION/SELECTION STRUCTURES
Example of If-Then Statements
Example 2: Determine the value that will be shown in txtComparisonOutput given the following code on the right. Note that the answer is True due to the OrElse shortcut operator.
DECISION/SELECTION STRUCTURES
Example of If-Then Statements
Example 3: Determine the value that will be shown in txtComparisonOutput given the following code on the right. Note that the answer is False due to the OrElse shortcut operator.
DECISION/SELECTION STRUCTURES
Example of If-Then Statements
For conditions with simple single-statement branches and no ElseIf clauses, a single-line alternative can keep the code look clean Example:
If (SaveData()=True Then MsgBox (“Data Saved.”)
If (TimeOfDay >= #17:00# _
Then currentStatus = WorkStatus.GoHome _
Else currentStatus = WOrkStatus.BusyWorking
Note that using an underscore or “_” at the end of program line in a code allows the code to be continued on the next line.
DECISION/SELECTION STRUCTURES
Some Notes on If-Then Statements
The key in reading and writing If-Then statements is understanding how comparison and logical operators work. Make sure you understand them and know the order precedence of each operator. If-Then statements follow the general rule of Visual BASIC in setting operation priority in reading program statements: Top to bottom between lines and left to right within a line (if equal precedence). Please read your Pre-Lab Handout and do the sample programming exercise. If-then statements and operators are thoroughly discussed in Exercise 2 Pre-lab Handout.
DECISION/SELECTION STRUCTURES
Select Case Statements
Select Case Decision Structure provides a cleaner alternative for single value comparisons against a list of several objects or a single object compared against different values. Syntax:
Select [ Case ] testexpression [ Case expressionlist1 [ statements 1] ] [ Case expressionlist2 [ statements 2] ] [ Case Else [ elsestatements ] ] End Select
DECISION/SELECTION STRUCTURES
Select Case Statements
Note that the listexpression can be as follows:
1. Exact Values. Example: Case 1 2. Different Values. Example: Case 1, 5, 9 3. Range of Values. Example: Case 2 To 5 Use the To keyword to specify the boundaries of a range of match values for testexpression. 4. Condition. Example: Case Is >= 2 Use the Is keyword with a comparison operator (=, , =) to specify a restriction on the match values for testexpression. If the Is keyword is not supplied, it is automatically inserted before comparison operator.
DECISION/SELECTION STRUCTURES
Example of Select Case Statements
Example 1: The code on the right illustrates that a variable (intOutput) is evaluated against different values. For sngInput = 108, the backcolor of the form will become Blue.
DECISION/SELECTION STRUCTURES
Example of Select Case Statements
Example 2: The code on the right illustrates that a value is evaluated against different objects.
DECISION/SELECTION STRUCTURES
Converting Selection/Decision Structures
The If-Then and Select Case statements on the right are equivalent. Take note how parentheses or “()” was used to group condition and expression list to override the rule of precedence. blnDecision will be True at the end of the expression.
REPETITION STRUCTURES
Loop Statements
Loop structures allow the computer to execute one or more lines of code repetitively. The statements can repeated until a condition is true, until a condition is false, at a specified number of times, or once for each object in a collection. The loop structures supported by Visual Basic include: 1. For...Next 2. For Each...Next 3. Do...Loop
REPETITION STRUCTURES
For-Next Loop Statements
Uses a numeric counter that increments from a starting value to an ending value, processing the code within the loop once for each incremented value If the increment isn’t specified, counter is incremented by 1. Syntax:
Begin
Counter = Start
Counter += Step
Statement
No
Counter = End?
Yes
Exit
For [counter = start] To end [Step increment] [Statements] Next [counter]
REPETITION STRUCTURES
For-Next Loop Statements
Example 1: The example below shows the basic algorithm for summation:
20
Dim X As Long = 0
������ =
������=1
5������
For Y As Byte = 1 To 20 X += 5 * Y Next
REPETITION STRUCTURES
Some Notes on For-Next
Start, End and Step increment
- must be numeric of the counter data type - can be positive or negative (limited by data type) - integer or non-integer (limited by data type)
Conditions for the loop to proceed
1. If stepvalue is positive, then startvalue must be less than or equal to endvalue. For intCount = 1 To 3 Step 0.5 2. If stepvalue is negative, then startvalue must be greater than or equal to endvalue.
For intCount = 3 To -2 Step -0.5
REPETITION STRUCTURES
For-Next Loop Statements
Example 2: The example below shows the basic algorithm for factorials:
������������!
'1 as initial value to prevent 0 end value Dim dblFactorial As Double = 1 'For general factorial algorithms,add an If-Then statement:
'if dblFactorial = 0 Then dblFactorial = 1
For intCounter As Integer = 15 To 1 Step -1
dblFactorial *= intCounter
Next
REPETITION STRUCTURES
For-Each Loop Statements
A variation of For Loop that scans through a set of ordered and related items, from the first item until the last. Syntax:
For Each element [ As datatype ] In Collection [ statements ] Next [ element ] The elements of collection can be of any data type. The data type of element must be such that each element of the collection can be converted to it.
REPETITION STRUCTURES
For-Each Loop Statements
Example:
This code search for all control objects in a form and changes all the backcolor to lightblue.
Sub LightBlueBackground(ByVal ThisForm As _ System.Windows.Forms.Form)
Dim ThisControl As Control For Each ThisControl In ThisForm.Controls ThisControl.BackColor = _ System.Drawing.Color.LightBlue Next ThisControl End Sub
REPETITION STRUCTURES
Do Loop Statements
Unlike For-Next which repeats a block of statements with definite number of times, Do-Loop executes a block of statements at an indefinite number of times depending on the Boolean value of a condition. It has two forms: 1. Do While: Repeats a block of code as long as a certain condition is True. 2. Do Until: Repeats a block of code until a condition is True
REPETITION STRUCTURES
Do Loop Statements
Pre-test Loops Evaluates the condition before processing any of the instructions within the loop Syntax:
Do While [condition] [Block of statements] Loop Do Until [condition] [Block of statements] Loop
REPETITION STRUCTURES
Do Loop Statements
Pre-test Loops Example:
20
Dim X As Long, Y As Byte