You are on page 1of 47

Control Structures In Visual

Basic
Control Structures
• Control structures allow you to regulate the flow of your program's
execution.
• Using control structures, you can write Visual Basic code that makes
decisions or that repeats actions.
• Other control structures let you guarantee disposal of a resource or
run a series of statements on the same object reference.
• Control Structures can be broadly grouped into
• Decision Structures
• Loop Structures
• Nested Control Structures
Decision Structures
• They are control structures that test a condition then make a decision
based on the results obtained from the tested condition.
• The following illustration shows a decision structure that tests for a
condition being true and takes different actions depending on
whether it is true or false.
Flow chart of Decision Structures
Types of Decision Structures
If...Then selection structure
• The If...Then selection structure performs an indicated action only
when the condition is True; otherwise the action is skipped.
• It only considers one condition
• Syntax of the If...Then selection
• If <condition> Then
statement
End If
Flow chart
.

Start

Condition
Action

No

Exit True
Example
• Think of a program that grades student as pass if they achieve 50
marks and outputs this decision in in a message Box. The G.U.I would
look as follows.
Cont.
• The program would look as follows
Dim marks As Integer = TextBox1.Text
If marks > 49 Then
MessageBox.Show("Pass")
End If
If...Then...Else selection structure
• The If...Then...Else selection structure allows the programmer to
specify that a different action is to be performed when the condition
is True than when the condition is False.
• Syntax of the If...Then...Else selection
• If <condition > Then
statements
Else
statements
End If
Flow Chart
Example 2 (If..Then..Else)
• The same program in example one but now also informing the user
that s/he has failed in case they don’t get above 50.
Dim marks As Integer = TextBox1.Text
If marks > 49 Then
MessageBox.Show("Pass")
Else
MessageBox.Show("Fail")
End If
Task
• Write a VB.Net program that allows the user to input two numbers
then the program outputs the largest of the two numbers.
The code
Dim num1 As Double = TextBox1.Text
Dim num2 As Double = TextBox2.Text
If num1 > num2 Then
TextBox3.Text = num1
Else
TextBox3.Text = num2
End If
Cont.
• The following is the G.U.I showing the output.
Multiple If...Then...Else selection structure
• Multiple If...Then...Else selection structures test for multiple cases by
placing If...Then...Else selection structures inside If...Then...Else structures.
• Syntax of the Nested If...Then...Else selection structure
Method 1/ Approach 1
If < condition 1 > Then
statements
ElseIf < condition 2 > Then
statements
ElseIf < condition 3 > Then
statements
Else
Statements
End If
Cont.
Method 2/ Approach 2
If < condition 1 > Then
statements
Else
If < condition 2 > Then
statements
Else
If < condition 3 > Then
statements
Else
Statements
End If
End If
EndIf
Flow chart
Example to Grade a student based on their
marks using MUT grading Criteria
Dim marks As Integer = TextBox1.Text ElseIf marks > 49 Then
If marks > 100 Then MessageBox.Show("D")
MessageBox.Show("invalid") ElseIf marks < 50 Then
ElseIf marks > 79 Then MessageBox.Show("Fail")
MessageBox.Show("A") Else
ElseIf marks > 69 Then
MessageBox.Show("B") MessageBox.Show("Invalid")
ElseIf marks > 59 Then End If
MessageBox.Show("C")
Cont. Snippets of the output
Select...Case selection structure
• Select...Case structure is an alternative to If...Then...ElseIf for
selectively executing a single block of statements from among
multiple block of statements.
• Select...case is more convenient to use than the If...Else...End If. The
following program block illustrate the working of Select...Case.
• Syntax of the Select...Case selection structure
• Select Case Index
Case 0
Statements
Case 1
Statements
End Select
Example: Assume you have to find the grade
using select...case and display in the text box
Dim total_marks as double Case 59 To 50
total_marks= marks.Text MessageBox.Show(“D")
Select Case total_marks Case 49 To 0
Case 100 To 80 MessageBox.Show(“Fail")
MessageBox.Show("A") Case Else
Case 79 To 70 MsgBox "Invalid average
MessageBox.Show(“B") marks"
Case 69 To 60 End Select
MessageBox.Show(“C")
Task
• Consider a real life learning scenario in MUT where students sit for
CATs, Assignments, and final examination. Create a windows form
application that allows the user to enter the marks for CAT1, CAT2,
Assignment, and Final Exam marks. The program then calculates the
total marks and grades the student using the MUT grading criteria.
LOOP CONTROL STRUCTURES
Cont.
• Visual Basic loop structures allow you to run one or more lines of
code repetitively.
• You can repeat the statements in a loop structure until a condition is
True, or until a condition is False, a specified number of times, or
once for each element in a collection.
Flow chart for loop Structures
While…End loop
• Runs a series of statements as long as a given condition is True.
• Use a While...End While structure when you want to repeat a set of
statements an indefinite number of times, as long as a condition remains
True.
• Syntax:
While condition
[ statements ]
[ Continue While ]
[ statements ]
[ Exit While ]
[ statements ]
End While
Example: A while loop program to output
numbers 0-10
Dim index As Integer = 0
While index <= 10
Console.Write(index.ToString & " ")
index += 1
End While

Console.ReadKey ()
Output
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
While Loop in a Windows Form Application
• Think of a windows form application that has button. When the
button is clicked it executes the while loop to output values from 1-10
as shown in the figure below.
The code for the button
Dim index As Integer = 0 • The first line declares the starting
Dim output As String point.
While index <= 10 • Second line creates a variable
known as output to store the
output = output & index & output.
vbNewLine • Third line starts the while block
index += 1 • Fourth line assigns the output after
End While each loop to the output variable
MessageBox.Show(output) through concatenation.
• Fifth line increments
• Seventh line is the message box for
outputting
Do…Loop
• It executes the statement at least once before checking the condition
Syntax

Method 1 Method 2
Do { While | Until } condition Do
[ statements ] [ statements ]
[ Continue Do ] [ Continue Do ]
[ statements ] [ statements ]
[ Exit Do ] [ Exit Do ]
[ statements ] [ statements ]
Loop Loop { While | Until } condition
Example: using Method 1
Dim a As Integer = 0
Do While a <= 10
Console.WriteLine("value of a: {0}", a)
a=a+1
Loop
Console.WriteLine("")
Console.ReadKey()
' Output: 0 1 2 3 4 5 6 7 8 9 10
Example: Using Method 2
Dim a As Integer = 0
Do
Console.WriteLine("value of a: {0}", a)
a=a+1
Loop While (a < =10)
Console.ReadLine()
' Output: 0 1 2 3 4 5 6 7 8 9 10
Note
• Method 1 is more or less like a • Method 2 is a true Do…While loop
while loop. • Which means it first executes at
• Which means that the program will least ones before evaluating the
evaluate the condition before condition.
executing the statements. • Thus if we set the value of integer
• Thus it will first check if the value to be 11 it will output 11 then stop
of integer is less than or equal to executing since 11 violates the
10 before outputting anything. condition.
• So if we set the value of integer to
be 11 then it will not output
anything
Do…While using Windows Form Application
• Use the form design used in while loop
• The code
Dim index As Integer = 0
Dim output As String
Do
output = output & index & vbNewLine
index += 1
Loop While (index <= 10)
MessageBox.Show(output)
For…Next Statement
• Repeats a group of statements a specified number of times.
• Very useful in defining ranges of elements to be considered
• Syntax:
For counter [ As datatype ] = start To end [ Step step ]
[ statements ]
[ Continue For ]
[ statements ]
[ Exit For ]
[ statements ]
Next [ counter ]
Flow Chart
Example
• In the following example, the index variable starts with a value of 1
and is incremented with each iteration of the loop, ending after the
value of index reaches 5.

For index As Integer = 1 To 5


Console.WriteLine(index.ToString & " ")
Next
Console.WriteLine("")
Console.ReadKey()
• Output: 1 2 3 4 5
For…Next Windows form Application
• The design and output of the program
The Code
Dim output As String
For index As Integer = 1 To 5
output = output & index & vbNewLine
Next
MessageBox.Show(output)
For…Each control structure
• Repeats a group of statements for each element in a collection.
• Mainly used when dealing with collection of elements such as in an
array.
• Arrays will be discussed in subsequent topics
For Each element [ As datatype ] In group
[ statements ]
[ Continue For ]
[ statements ]
[ Exit For ]
[ statements ]
Next [ element ]
Example: Printing values of an array
Dim anArray() As Integer = {1, 3, 5, 7, 9}
Dim arrayItem As Integer
For Each arrayItem In anArray
Console.WriteLine(arrayItem)
Next
Console.ReadLine()
• it will output 1,3, 5, 7, 9 which are the values in the array called
“anArray”
More Advanced Loop Operation using Windows
Form Applications
• Think of a situation in which rather than declaring the starting points
and end points of the loops in the code you allow the user to input
them from a G.U.I.
• The benefit of such a program is that it would be more dynamic since
you can adjust the ranges while the program is still executing.
• How would you go about creating the program?
• All you need is to add two textboxes: one to handle the starting point and the
other one to handle the ending point.
• Then create local variables for the starting points and end points.
• Use those local variables as your ranges in the loop
The Design and the Code of the program
The design • The Code
Dim startpoint As Integer = TextBox1.Text
Dim endpoint As Integer =
TextBox2.Text
Dim output As String
While startpoint <= endpoint
output = output & startpoint &
vbNewLine
startpoint += 1
End While
MessageBox.Show(output)
The Execution and Output
Research Task
• Sometimes an application user may accidentally click the Exit button
of an application and it is therefore wise to provide the application
with a facility like the dialog box shown below. Study it and develop
an event procedure of the exit button that triggers the dialog box.
Conclusion
Practice more on each of these control structures.

You might also like