Wednesday, 11 January 2012

Control Statements


VB.Net has statements such as If .. Then ..else and Select …. Case, which help you to
conditionally execute program.
VB.Net provides you with various looping statements, such as Do… Loop, While…. End
While, and For… Next.
1. The If….Then….Else…End if Statement
Consider a student marks and grade evaluation. For Marks above 75 the grade is ‘A’ and
for below 75 is ‘B’. In this situation when you need to execute some code based on some
condition, you can make use of, If…then…else…end if.
The Cultural syntax normally used is as follows:
If condition Then
Executable statements when the condition is True
Else
Executable statements when the Condition is False
End If
OR using Elseif for Advanced Decision making
If condition Then
Executable statements
ElseIf condition Then
Executable statements
End If
Single if can have multiple else with conditions, as mentioned above in elseif format and
finally a single End If for the main If condition.
Nesting IF…Then Constructs
If condition Then
If condition2 Then
Executable statements when the condition2 is TRUE
Else
Executable Statements
End if
Else
Executable statements
End If
One important thing to keep in mind when nesting IF…Then constructs is that you must have corresponding End If statement for
every IF ..Then statement, unless the If then statement executes only one statement and that statement appears on the same line as
If…Then
2. The Select…Case Statement(Evaluating an Expression for Multiple Values)
The Select…Case Statement is similar to If…Else…End if. The only difference between
two is that If and elseif can evaluate different expressions in each statement, but the
Select statement can evaluate only one expression.
The drawback of IF...Then construct is that it isn’t capable of handling a decision
situation without a lot of extra work. One such situation is when you have to perform
different actions based on numerous possible values of an expression, not just True or
False. For instance performing actions based on Students Marks.
If intmarks >35 Then
…….
Elseif intmarks >50 then
……
Elseif intmarks>65 then
…..
Elseif intmarks>75 then

Else
….
End If
As you see the structure can be a bit hard to read and if the conditions increase you may
end up writing a confusing and an unreadable piece of Code
The Select uses the result of an expression to execute different set of statements.
The syntax for the Select…Case Statement is as follows:
Select Case [expression]
Case [expression list]
Executable statements.
Case Else
Executable statements.
Exit Select - to exit from the select
End Select
Note: Case Else is used to define the code that executes only when the expression doesn’t
evaluate to any of the values in Case Statements .Use of Case Else is optional
Lets see the same example as above but this time with Select Case
Select Case intmarks
Case Is >35
Executable statements
Case Is >50
Executable statements
Case Is>65
Executable statements
Case Is >75
Executable statements
Case Else
Executable statements
End Select
Evaluating More than one possible Value in a Case Statement
Select Case helps you to use some more advanced expression comparisons. Like,you can
specify multiple comparisons in a Single Case statement by just using comma. Lets see
how it does
Select Case strColor
Case Is=”Red”,”Blue”,”Magenta”
‘Color is a Dark Shade
Case Is =”Cream”,”white”
‘Color is a Cool Shade
End Select
Another comparison expression used is keyword To, Visual Basic.NET evaluates the
expression and finds out whether it is in the range mentioned and if yes the Statement is
executed. Please note that when using To, you can’t include Is = as you can with the
simple expression
Select Case intmarks
Case 1 to 35
‘Executable statements
Case 36 to 50
‘Executable Statements
End Select
3. For…Next Statement
The For…Next Statements are used repeat a set of statements for specific number of
times.
The syntax for the For…Next Statements is as follows:
For counter = <start value> to <end value> [Step Value]
Executable Statements
Exit For
Next [counter]
Counter is any numeric value.
Start value is the initial value of the counter.
End value is the final value of the counter.
Step Value is the value by which the counter is incremented. It can be positive or
negative. The default value is 1.
Exit For is used to exit the For…Next loop at any time. When Exit for is encountered
,the execution jumps to the statement following Next
Next is the statement the marks the end of the For statement. As soon as the program
encounters the Next statement, the step value is added to the counter and the next
iteration of the loop takes place.
Dim intctr as Integer
For intctr=1 to 100
Debug.WriteLine(intctr)
Next intctr
This routine starts a loop with a For statement after a variable intctr is declared. This loop
initializes intctr to 1 and then prints 1 through 100 to the output window. It prints in steps
of 1 as Step has been omitted here, so the default is 1
Example of use of STEP in For....Loop.
Let us write a table of 2 using step in for loop.
Add a label with name it as lbtables and make it bit bigger on the screen.
Dim j = 1
For i = 2 To 20 Step 2
Me.lbtables.Text = Me.lbtables.Text & "2 X " & j.ToString & " = " &
i.ToString & vbCrLf
j = j + 1
Next
Output:
2 X 1 = 2
..
..
..
..
..

2 X 10 = 20
An Example of Nested For loop.
Let us write a small code to display a structure of stars ‘*’ in triangle format.
*
* *
* * *
* * * *
* * * * *
* * * * * *
Let us have a label with name stars. Increase the height of the label to get a clear view of
the image.
Dim star As String
Dim i, j As Integer
For i = 0 To 5 ' First loop to count the rows
For j = 0 To i ' Second loop to count the columns
star = star & " * "
Next
Me.stars.Text = Me.stars.Text & star & vbCrLf ' To print *
star = ""
Next
4. For Each…Next Statement
The For Each…Next Statement is used to repeat a set of statements for each element in
an array or collection.
The For Each…Next statement is executed if there is at least one item in an array of
collection.
The Loop repeats of each element in an array or collection.
The syntax for the For Each…Next statement as follows:
For Each Component In Set
Executable statements
Next
Component is the variable used to refer to the elements of an array or a collection.
Set refers to an array or any collection object. e.g.
Dim weeks() As String = {"Monday", "Tuesday", "Wednesday", "Thursday",_
"Friday", "Saturday", "Sunday"}
Dim eachday As String
For Each eachday In weeks
MsgBox(eachday)
Next
An example for using for each element in a collection of string into a single string
element.
Each element of array which is of type string is read from the collection and stored into
the single string type object.
5. While…End Statement
The While…End Statement is used to repeat set of executable statements as long as the
condition is true.
The syntax for the While…End statement is as follows:
While Condition
Executable Statements
End While
In this if the condition is satisfied then the statements are executed. Else it will not
enter the While condition at all.
6. Do...Loop Statement
The Do…Loop Statement is similar to While…End. Here we have two types of
formatting the loop.
a) Do While / Until Condition Executable Statements Loop
b) Do Executable Statements Loop While/Until Condition
The Difference is in a) The loop will be executed if the condition is satisfied, but in b)
The Loop will be executed at least once even if the condition does not satisfy.
Do While Expression
[Statements]
Loop
Do Until Expression
[Statements]
Loop
Note: For VB programmers While Wend is not supported it is While… End now
A Complete Example with set of control statements.
We will create a VB.Net application, which will accept students name and its grade.
Depending up the type of grade it will add remarks.
txtsummary.Text = ""
Dim value, ctr As Integer
'Accept a number from the user
value = CInt(InputBox("Enter the number of students"))
'Check if the validity of the number
If value <= 0 Then
MsgBox("Enter details of at least one student", "Error")
End If
Dim arrName(value) As String
Dim sGrade As String
Dim arrRemarks(value) As String
While ctr < value
'Accept the name of the students
arrName(ctr) = InputBox("Enter the name of the Student"_
& ctr + 1, "Enter Details")
'Accept the grade of the Student
sGrade = InputBox("Enter the grade of the student" &
"(_A/B/C/D/F)", "Grade Details")
' Assign remarks to students
Select Case UCase(sGrade)
Case "A"
arrRemarks(ctr) = "Excellent"
Case "B"
arrRemarks(ctr) = "Good"
Case "C"
arrRemarks(ctr) = "Fair"
Case "D"
arrRemarks(ctr) = "Poor"
Case "F"
arrRemarks(ctr) = "Fail"
Case Else
MsgBox("Incorrect value entered ", _
MsgBoxStyle.Critical)
Exit Sub ' To come out of the program
End Select
ctr = ctr + 1
End While
' Display the summary in the text box
For ctr = 0 To value - 1
If txtsummary.Text = "" Then
If LCase(arrRemarks(ctr)) = "fail" Then
txtsummary.Text = arrName(ctr) & " has failed _
in exams" & vbCrLf
Else
txtsummary.Text = arrName(ctr) & "'s performance is_
" & arrRemarks(ctr) & vbCrLf
End If
Else
If LCase(arrRemarks(ctr)) = "fail" Then
txtsummary.Text = txtsummary.Text & arrName(ctr) &_
" has failed in exams" & vbCrLf
Else
txtsummary.Text = txtsummary.Text & arrName(ctr) &_
"'s performance is " & arrRemarks(ctr) &_ vbCrLf
End If
End If
Next