Controlling Program Flow Part 1
© Peter Bilbie 2010
Contents
Introduction - Sequence Selection & Iteration 3
Sequence 3
Selection 3
Iteration 3
IF Statements 4
Multiple Conditions using AND, OR and NOT 5
Comparison Operators 6
Concatenation Operator 7
Built in Functions 8
Nested IF Statements 9
Exercise 1 10
ELSEIF Statements 11
Practice\Exercise 12
Summary 13
Controlling Program Flow Part 1
Introduction - Sequence Selection & Iteration
During the previous sessions we have covered the very basics of programming in VB .NET. During the next few sessions we will be looking at the basic building blocks used for all types of programming languages – sequence, selection and iteration. The syntax for each language may be different but the concepts are the same.
Sequence
All programs run through each line of code sequentially i.e. one line after another. When we run a VB .NET program and invoke an event i.e. click a button, the program will run through the event code line by line until it reaches the End Sub statement of the event. Within the event code there may be loops and calls to other functions or procedures but it will return to the next line after visiting the other procedures and continue until the End Sub is reached. The program will then be static until another procedure is invoked.
Selection
These are mechanisms that let you make a choice i.e. if student arrives before the start of a class then feint otherwise carry on as normal.
The two types of selection statements are:
· If statements
· Select Case statements
If statements will be covered in more detail later on in this session
Iteration
To iterate means to repeat and in programming you may want to iterate through a piece of code either to increment values, access and update records in a database, add items from a file to a list box or other display control etc.
There are various types of looping structures that can be used in VB .NET
· For Next Loops – determinate loops whereby the number of iterations is determined at the start of the loop.
· Do While Loops – indeterminate loops that check a condition at the start of the loop and if the condition is true the code inside the loop will be invoked. This means that if the condition is false the first time through the loop code may never be invoked
· Do Loop Until – also indeterminate except that the condition is checked after the loop has been through one cycle, therefore it invokes the code inside the loop at least once
For this session we will be looking at the use of ‘If statements’ and iteration will be covered in later sessions
IF Statements
Before we start this subject, create a new form in your MDI projects and name it FrmSelection. Add two textboxes and a command button – txtFirst, txtSecond and btnTry
The basic structure of an IF statement is:
IF <a condition> THEN
<run code>
END IF
The condition must return ‘True’ for the code to be run otherwise the code is ignored. For example, if we want to compare the value entered into two textboxes for equality we could use the following syntax:
IF txtFirst.Text = txtSecond.Text THEN
Messagebox.Show(“Both the same”)
END IF
Use your program to create the code above – you will need to enter it into the click event of the button – see below
Private Sub btnTest_Click(…
If txtFirst.Text = txtSecond.Text Then
MessageBox.Show("The Same")
End If
End Sub
Run the program, add two identical number or text values in the textboxes and click the Test button – see output below
However if we input two dissimilar number or text values nothing happens.
What we need is some facility to inform the user of the result if it is false. This is done by adding an ELSE statement
The syntax for this is shown below:
If txtFirst.Text = txtSecond.Text Then
MessageBox.Show("The Same")
Else
MessageBox.Show("Different”)
End If
The output is:
Multiple Conditions using AND, OR and NOT
It is possible to evaluate multiple conditions using the logical operators AND, OR, and NOT. The extended logical statements are placed on the first line of the IF statement i.e.
IF X > Y AND Y > 10 AND X < 5 THEN
Which reads – if X not equal to (>) Y and Y greater than 10 (>) and X is less than 5 (<)
This example has a mixture of logical and comparison operators. Other comparison operators are show below:
Comparison Operators
Operator / MeaningLess than
<= / Less than or equal to
Greater than
>= / Greater than or equal to
Not equal to
= / Equal to
The logical OR is used in the same way as the AND except that only one of the conditions needs to be true i.e.
If IsNumeric(txtFirst.Text) Or IsNumeric(txtSecond.Text) Then
MessageBox.Show("At least one is a number")
Else
MessageBox.Show("Neither are Numbers")
End If
With the result:
The logical NOT statement checks to see if something is different to what is stated i.e.
If Not txtFirst.Text = txtSecond.Text Then
MessageBox.Show("Values are different")
Else
MessageBox.Show("Values are the same")
End If
VB .NET has introduced another set of logical operators AndAlso and OrElse. These are used in place of the AND and OR when there are multiple conditions..
The AndAlso will evaluate each condition and as soon as one condition is false it does not evaluate the remainder of the conditions and the program generates the ELSE statement message.
The OrElse statement will evaluate each condition and as soon as it finds one that is true it executes the next line of code.
The AndAlso and OrElse statements are nothing more time saving devices
The problem with multiple condition statement is that because they have to be on the same line the code can get difficult to read. To make things easier VB .NET has a function that allows you to place code on separate lines while the compiler still evaluates the code as a single line. To use it find a suitable place to split your code and put a space then an underscore then another space and then press Enter. An example is shown below:
cond.Text) _ And (txtF
The full code is shown below
Private Sub btnTest_Click(…
If IsNumeric(txtFirst.Text) And IsNumeric(txtSecond.Text) _
And (txtFirst.Text = txtSecond.Text) Then
MessageBox.Show("The Same Numbers")
Else
MessageBox.Show("Different Numbers or " _
& "Text Values have been entered")
End If
End Sub
Concatenation Operator
When dealing with string values (see above in the ELSE part of the statement) you must add speech marks then a space then the underscore then press enter. At the beginning of the new line add an ampersand (&) and another set of speech marks. Used for this purpose the ampersand character is known as a concatenation operator. Concatenation means to join
The code above has three ANDED conditions which all have to evaluate to true. All ANDED conditions must be True before the next line of code is executed otherwise the ELSE code is executed.
Built in Functions
If you study the code above you will see I have used an In-Built Function – IsNumeric to evaluate the values in the textboxes for numeric values. If the values are not numeric then the function returns False – this is what is known as a Boolean Function as it returns true if the value is numeric or false otherwise. There are many pre-written built in functions to use in your programs. Another useful function is the IsDate function which is used to check that whatever is placed in the brackets is in a correct date format i.e. IsDate(“01/10/2010”) will return True, IsDate(4z) returns False
Nested IF Statements
We can nest IF statements which allows us to have multiple entry and exit points. For example, if we had a situation where two values entered by the user in two textboxes have to be numeric, be different values, the first one has to be smaller than the second and they both have to be greater than 20. If we wrote an ANDED statement there is only one ELSE message – what would be displayed if one of the conditions were false?
With the nested if we can have multiple messages – see below:
If IsNumeric(txtFirst.Text) Then
If IsNumeric(txtSecond.Text) Then
If txtFirst.Text > txtSecond.Text Then
If txtSecond.Text > txtFirst.Text Then
If txtSecond.Text > 20 Then
If txtFirst.Text > 20 Then
MessageBox.Show("All Systems Go")
Else
MessageBox.Show("First Number less than 20")
End If
Else
MessageBox.Show("Second Number less than 20")
End If
Else
MessageBox.Show("First Number greater than Second")
End If
Else
MessageBox.Show("Second Number Same as First")
End If
Else
MessageBox.Show("Second Number Not Numeric")
End If
Else
MessageBox.Show("First Number Not Numeric")
End If
All IF’s have a THEN on the end of the line of code.
All IF’s have their own ELSEs and END IF’s which should line up.
If all the conditions are true then the code after the last IF is executed
You will find that you will use this type of structure when you are Validating User Input during testing.
Below is a test harness to check each condition:
You do not necessarily have to copy examples of all your testing as shown above but you will almost certainly have to create a test plan and log all the tests. Testing will be covered in another session
Exercise 1
A program is required to calculate a student’s grade from a given mark. The grades are calculated as below:
Mark / Grade0 – 39 / Fail
40 – 55 / D
56 – 65 / C
66 – 75 / B
76 – 85 / A
86 – 100 / A*
Add anther form to your program and name it frmGrades with 2 textboxes, txtMark and txtGrade and a button btnCalculate. Create the code for the click event of the Calculate button. The user will enter a mark in the 1st textbox, click Calculate and the corresponding grade is to be calculated and assigned to the 2nd textbox
ELSEIF Statements
Situations where we have several conditions whereby different code is executed dependent on each condition then a neater solution is to use an ELSEIF statement.
The ELSEIF makes the coding much simpler and easier to read. The code below shows the structure of the ELSEIF
If mark < 40 Then
grade = "Fail"
ElseIf mark < 56 Then
grade = "D"
ElseIf mark < 66 Then
grade = "C"
ElseIf mark < 76 Then
grade = "B"
ElseIf mark < 86 Then
grade = "A"
ElseIf mark <= 100 Then
grade = "A*"
Else
grade = 0
End If
The final code below shows the declaration of two variables grade as string and mark as integer. The user will be adding marks in the first textbox and the result is displayed in the second textbox. There is also Validation of the first textbox input using the IsNumeric function. If a numeric value has been input the value is assigned to the variable mark
Dim mark As Integer
Dim grade As String
If IsNumeric(txtFirst.Text) Then
mark = txtFirst.Text
If mark < 40 Then
grade = "Fail"
ElseIf mark < 56 Then
grade = "D"
ElseIf mark < 66 Then
grade = "C"
ElseIf mark < 76 Then
grade = "B"
ElseIf mark < 86 Then
grade = "A"
ElseIf mark <= 100 Then
grade = "A*"
Else
grade = 0
End If
txtSecond.Text = grade
Else
MessageBox.Show("Numeric values only")
End If
Practice\Exercise
1. Complete all the exercises above
2. Create another form in your MDI program and create an interface to help an indecisive person make a decision. When the person gets up in the morning he wants to know what actions to take depending on certain factors
a. If it’s a weekend – go back to bed
b. If it’s a working day – check weather forecast
c. If it’s forecast sunny all day – walk to work
d. If it’s forecast rain all day – take car
e. If it’s forecast fair – take umbrella and walk to work
Summary
We have covered a great deal in this session including:
· Sequence, selection and iteration
· If-End if statements
· If-Else-End if statements
· Logical operators
· Comparison operators
· Concatenation
· AndAlso and OrElse
· Nested If statements
· If-Else If statements
· Validation of user input
· Assigning values to variables
Next session we will be covering Case Statements
© Peter Bilbie – 2010 Page 12 of 13