Professional Documents
Culture Documents
DECISION MAKING
Decision Statements (Conditional Statement)
• Applications need a mechanism to test conditions, and they
take a different course of action depending of the outcome of
the test.
• Visual Basic Provides three statement that allow you to alter
the course of the application based on the outcome of a
condition:
If…Then
If…Then…Else
Select Case
IF…THEN STATEMENTS
The If…Then statement tests an expression, which is known as a
condition.
To execute one statement conditionally, use the single-line
syntax as follows:
If condition then statement
To execute multiple statements conditionally, embed the
statements within an If and End If statement, as follows:
If condition Then
` Statement
` Statement
End If
Here are a few examples of valid conditions:
Case DayofWeek.Monday
Message=”Have a nice weekend”
Case Else
Message= “Welcome back!”
End Select
MsgBox(message)
LOOP STATEMENTS
• Loop statements allow you to execute one or more lines of
code repetitively.
• Many task consists of operation that must be repeated over
and over again, and loop statements are an important part of
any programming language.
• Visual Basic supports the following loop statements:
For..Next
Do…loop
While …End while
FOR NEXT LOOP
• Unlike the other two loops, the For …Next loop requires that
you know the number of time that the statement in the loop
will be executed.
• The For…Next loop has the following syntax:
For counter = start to end [Step increment]
‘ statements
Next [counter]
• The keywords in the square brackets are optional.
The For..Next loop scans all the elements of the numeric array
data and calculates their average.
Iterating an array with a For next loop
Dim i As Integer, total as Double
For i=0 To 10
Total = total+1
Next
console.writeline (total)
FOR EACH….NEXT LOOPS
This is a variation of the classic For loop and it’s used to iterate
through the items of a collection of array. Let’s say you have
declared an array of strings like the following :
While condition
Statement-block
End While
Dim number, total As Double
Number = 0
While number => 0
total = total +number
number = InputBox(“Please another value”)
End while
Dim repeatLoop As Boolean
repeatLoop = True
While repeatLoop
Statements
If condition Then
repeatLoop = True
Else
repeatLoop = False
End If
End While
Dim a As Byte
' for loop execution
For a = 10 To 20
Console.WriteLine("value of a: {0}", a)
Next
Console.ReadLine()
• value of a: 10
• value of a: 11
• value of a: 12
• value of a: 13
• value of a: 14
• value of a: 15
• value of a: 16
• value of a: 17
• value of a: 18
• value of a: 19
• value of a: 20
Dim a As Byte
' for loop execution
For a = 10 To 20 Step 2
Console.WriteLine("value of a: {0}", a)
Next
Console.ReadLine()
value of a: 10
value of a: 12
value of a: 14
value of a: 16
value of a: 18
value of a: 20
Dim i, num As Integer
Num=5
For i = 1 To 10
Console.WriteLine(num & " * " & i & " = " & i * num)
Next
Dim a As Integer = 10
While a < 20
Console.WriteLine("value of a: {0}", a)
a=a+1
End While
Console.ReadLine()
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
DO Loops
• The Do Loop statement executes a block of statements for as
long as the condition is True or until a condition becomes True.
• To execute a block of statements while a condition is True, use
the following syntax:
Do While condition
Statement-block
Loop
To execute a block of statements until the condition becomes
True, use the following syntax:
Do Until condition
Statement-block
Loop
The Do…While loop is executed when the condition is True, and
the Do…Until loop is executed when the condition is False.
A last variation of the Do statement, the Do…Loop statement,
allows you to always evaluate the condition at the end of the
loop, even in a While loop. Here’s the syntax of both types of
loop, with the evaluation of the condition at the end of the loop.
Do
Statement-block
Loop While condition
Do
Statement-block
Loop Until condition
1. Do While intX < 3
intX += 1
Loop
2. Do Until intX = 3
intX += 1
Loop
3. Do
intX += 1
Loop Until intX = 3
Nested Control Structure
• You can place, or nest, control structures inside other control
structures (such as an If…Then block within a For…Next loop)
or nest multiple If…Then blocks within one another.
• Control structures in Visual Basic can be nested in as many
levels as you want.
• When you nest control structures, you must make sure that
they open and close within the same structure.
• In other words, you can’t start a For…Next loop in an If
statements and close the loop after the corresponding End If.
For a = 1 to 100
Statements
If a = 99 Then
Statements
End If
While b < a
Statements
If total <=0 Then
Statements
If total <= 0 Then
Statements
End While
For c = 1 to a
Statements
Next c
Next a
The exit and Continue statements
• The exit statement allows you to prematurely exit from a block
of statements in a control structure, from a loop, or event
from a procedure.
• Suppose that you have a For Next Loop that calculates the
square root of a series of numbers. Because the squareroot of
negative numbers cant’ be calculated (the Math.Sqrt method
will generate a runtime error), you might want to halt the
operation if the array contains an invalid value.
For I = 0 To UBound(nArray)
If narray(i) < 0 Then
msgBox(Can’t complete calculations” & vbCrLf &
“Item “ & i.ToString & “ is negative! “)
Exit For
End If
Next
• Sometimes you may need to continue with the following
Iteration instead of exiting the loop(in other words, skip
the body of the loop and continue with the following
value).
• In these cases, you can use the Continue statement
(Continue For for For….next loops, Continue while for
while loops, and so on.
VB.Net- STRING
• A string is nothing but a collection of characters.
• In very simple terms, String may be defined as the array
of characters.
• When it comes to an understanding variable, Integer is
the very first thing we learn about.
• An integer is the data type that stores the integer value,
in the same way, char is the data type that stores single
character and similarly, a string is the data type that
allows the storage of the set of characters in a single
variable.
Declaration and Initialization of
VB.Net
• To bring string in actual use, we will first need to declare
the string.
Dim Str as String
• Now, once the name of the variable is declared we have
to put some value in it so that it could be used in the
program. Str=“Latin”
• Once the values are assigned, we can use it anywhere in
the program.
Working with VB.Net String Functions
String Description Example
Function
Asc This string function in VB.Net is Asc(Str)
used in order to get the integer Output: 76
value of the first letter of the string.
Format This function is used to arrange the Dim ChangedTime As Date =
string in a particular format #03/23/2019 4:10:43 PM#
Dim ChangedTime as the string
ChangedTime = Format(TestDateTime,
"h:m:s")
Output: 04:10:43 PM
Join This VB.Net String function is used Dim ItemList() As String = {“Apple”,
to join two substrings. “Banana”, “Guava”}
Dim JoinItemList as string = Join(ItemList,
", ")
Output: Apple, Banana, Guava
LCase This function will convert all the Dim Uppercase as String = “HELLO
characters of the string into a WORLD”
lowercase character. Dim Lowercase as String =
LCase(Uppercase)
Output: hello world
Left This function will return the Dim CheckStr as string = “Hey Jim”
specific characters from left Dim ResultStr as string =
as requested by mentioning Left(CheckStr, 3)
any number
Output: Hey
Len This String function in VB.Net Dim StrWords as String = “You are a
will return the numbers of hero!”
characters in a string. Dim WordCount as Integer =
Len(StrWords)
Output: 15
Right This function will return the Dim CheckStr as string = “Hey Jim”
specified number of Dim ResultStr as string =
characters from a string from Right(CheckStr, 3)
the right side.
Output: Jim
Split This String function in Dim CheckStr as String = “How are
VB.Net is used to split the you?”
string. Dim OutputStr as String =
Split(CheckStr)
Output: elppA
res = FindMax(a, b)
Console.WriteLine("Max value is : {0}", res)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it
produces the following result −
Max value is : 200
Recursive Function
• A function can call itself. This is known as recursion.
Following is an example that calculates factorial for a given number using a recursive
function
Module myfunctions
Function factorial(ByVal num As Integer) As Integer
' local variable declaration
Dim result As Integer
If (num = 1) Then
Return 1
Else
result = factorial(num - 1) * num
End If
Return result
End Function
Sub Main()
'calling the factorial method
Console.WriteLine("Factorial of 6 is : {0}", factorial(6))
Console.WriteLine("Factorial of 7 is : {0}", factorial(7))
Console.WriteLine("Factorial of 8 is : {0}", factorial(8))
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the
following result −
Factorial of 6 is: 720
Factorial of 7 is: 5040
Factorial of 8 is: 40320
Param Arrays
• At times, while declaring a function or sub procedure, you are
not sure of the number of arguments passed as a parameter.
• VB.Net param arrays (or parameter arrays) come into help at
these times.
Module myparamfunc
Function AddElements(ParamArray arr As Integer()) As Integer
Dim sum As Integer = 0
Dim i As Integer = 0
For Each i In arr
sum += i
Next i
Return sum
End Function
Sub Main()
Dim sum As Integer
sum = AddElements(512, 720, 250, 567, 889)
Console.WriteLine("The sum is: {0}", sum)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the
following result −
The sum is: 2938
Passing Arrays as Function
Arguments
• You can pass an array as a function argument in VB.Net.
• The array can be passed just like ordinary data type.
• The following example demonstrates this −
Module arrayParameter Sub Main()
Function getAverage(ByVal arr As ' an int array with 5 elements '
Integer(), ByVal size As Integer) As Dim balance As Integer() =
Double {1000, 2, 3, 17, 50}
'local variables Dim avg As Double
Dim i As Integer 'pass pointer to the array as an
Dim avg As Double argument
Dim sum As Integer = 0 avg = getAverage(balance, 5)
For i = 0 To size - 1 ' output the returned value '
sum += arr(i) Console.WriteLine("Average
Next i value is: {0} ", avg)
avg = sum / size Console.ReadLine()
Return avg End Sub
End Function End Module
• When the above code is compiled and executed, it produces
the following result −
• Average value is: 214.4
Subroutines
Sub ShowDate( )
MsgBox( “Today’s date is “ & Now( ). ToShortDateString)
End Sub
• To use it in your code, you can just enter the name of the
function in a line of its own:
ShowDate
Defining Sub Procedures
The Sub statement is used to declare the name, parameter and
the body of a sub procedure.
The syntax for the Sub statement is −