1. Shri Shivaji Science College, Amravati
Department of Computer Science
Topic- Decisions and loop
Prepared By
Dr. Ujwala S. Junghare
Assistant Professor
Dept. of Computer Science
2. In VB.NET, the control statements are the statements that controls the execution of the
program on the basis of the specified condition.
It is useful for determining whether a condition is true or not. If the condition is true, a single
or block of statement is executed.
In the control statement, we will use if- Then, if Then Else, if Then ElseIf and the Select
case statement.
We can define more than one condition to be evaluated by the program with statements. If the
defined condition is true, the statement or block executes according to the condition, and if the
condition is false, another statement is executed.
The following figure shows a common format of the decision control statements to validate
and execute a statement:
Controlling program flow, Conditional Statements
3. The above diagram shows that if the defined condition is true, statement_1 will be executed, and if the condition is
false, statement_2 will be executed.
VB.NET provides the following conditional or decision-making statements.
•If-Then Statement
•If-Then Else Statement
•If-Then ElseIf Statement
•Select Case Statement
•Nested Select Case Statements
4. If-Then Statement
The If-Then Statement is a control statement that defines one or more conditions, and if the particular
condition is satisfied, it executes a piece of information or statements.
Syntax:
If condition Then
[Statement or block of Statement]
End If
In If-Then Statement, the condition can be a Boolean, logical, or relational condition, and the statement
can be single or group of statements that will be executed when the condition is true.
5. Example 1: Write a simple program to print a statement in VB.NET.
Module1.vb
Module Module1
' Declaration of variable str
Dim str As String = "JavaTpoint"
Sub Main()
' if str equal to "JavaTpoint", below Statement will be executed.
If str = "JavaTpoint" Then
Console.WriteLine("Welcome to the JavaTpoint")
End If
Console.WritLine("press any key to exit?")
Console.ReadKey()
End Sub
End Module
6. If-Then-Else Statement
The If-Then Statement can execute single or multiple statements when the condition is true, but when
the expression evaluates to false, it does nothing. So, here comes the If-Then-Else Statement.
The IF-Then-Else Statement is telling what If condition to do when if the statement is false, it executes
the Else statement. Following is the If-Then-Else statement syntax in VB.NET as follows:
Syntax:
If (Boolean_expression) Then
'This statement will execute if the Boolean condition is true
Else
'Optional statement will execute if the Boolean condition is false
End If
7. Module decisions
Sub Main() 'local variable definition ‘
Dim a As Integer = 100
If (a < 20) Then
Console.WriteLine("a is less than 20")
Else
Console.WriteLine("a is not less than 20")
End If
Console.WriteLine("value of a is : {0}", a)
Console.ReadLine()
End Sub
End Module
8. This construct is similar to If . . . Then . . . Else, except that it offers a number of choices. The
construct is used as follows:
If Condition1 Then
Statement1
ElseIf Condition2 Then
Statement2
.
.
ElseIf Conditionk Then
Statementk
End If
The program will examine each condition in turn until it finds a condition that is true. Once a true
condition is found, and its statement has been executed, the program terminates the conditional
search at End If. If none of the conditions are true, a default condition can be provided by adding a
final Else section. The default condition must be the last in the list, and its associated statement will
be executed only if none of the other conditions are true.
The If . . . Then . . . ElseIf statement
If(condition 1)Then
' Executes when condition 1 is true
ElseIf( condition 2)Then
' Executes when condition 2 is true
ElseIf( boolean_expression 3)Then
' Executes when the condition 3 is true
Else
' executes the default statement when none of the above conditions is
true.
End If
9. The following diagram represents the functioning of the If-Else-If Statement in the VB.NET
programming language.
10. Private Sub Form1_Click (sender As Object, e As EventArgs) Handles Me.Click
If BackColor = Color.Red Then
BackColor = Color.Blue
ElseIf BackColor = Color.Blue Then
BackColor = Color.Green
ElseIf BackColor = Color.Green Then
BackColor = Color.Black
Else
BackColor = Color.Red
End If
End Sub
11. Module if_elseIf
Sub Main()
Dim var1 As Integer
Console.WriteLine(" Input the value of var1: ")
var1 = Console.ReadLine()
If var1 = 20 Then
'if condition is true then print the following statement'
Console.WriteLine(" Entered value is equal to 20")
ElseIf var1 < 50 Then
Console.WriteLine(" Entered value is less than 50")
ElseIf var1 >= 100 Then
Console.WriteLine(" Entered value is greater than 100")
Else
'if none of the above condition is satisfied, print the following statement
Console.WriteLine(" Value is not matched with above condition")
End If
Console.WriteLine(" You have entered : {0}", var1)
Console.WriteLine(" press any key to exit...")
Console.ReadKey()
End Sub
End Module
12. A Select Case statement allows a variable to be tested for equality against a list of values. Each value is called
a case, and the variable being switched on is checked for each select case.
The syntax for a Select Case statement in VB.Net is as follows −
Select [ Case ] expression
[ Case expressionlist
[ statements ] ]
[ Case Else
[ elsestatements ] ]
End Select
Where,
expression − is an expression that must evaluate to any of the elementary data type in VB.Net, i.e., Boolean, Byte, Char,
Date, Double, Decimal, Integer, Long, Object, SByte, Short, Single, String, UInteger, ULong, and UShort.
expressionlist − List of expression clauses representing match values for expression. Multiple expression clauses are
separated by commas.
statements − statements following Case that run if the select expression matches any clause in expressionlist.
elsestatements − statements following Case Else that run if the select expression does not match any clause in
the expressionlist of any of the Case statements.
Select Case
13.
14. Module decisions
Sub Main()
Dim grade As Char
grade = "B"
Select grade
Case "A"
Console.WriteLine("Excellent!")
Case "B", "C"
Console.WriteLine("Well done")
Case "D"
Console.WriteLine("You passed")
Case "F"
Console.WriteLine("Better try again")
Case Else
Console.WriteLine("Invalid grade")
End Select
Console.WriteLine("Your grade is {0}", grade)
Console.ReadLine()
End Sub
End Module
15. Module Module1
Sub Main()
Dim name As String
name = “Good"
Select Case name
Case "John"
Console.WriteLine("Hello John")
Case "Ggg11"
Console.WriteLine("Hello Ggg11")
Case "Alice"
Console.WriteLine("Hello Alice")
Case "Joel"
Console.WriteLine("Hello Joel")
Case Else
Console.WriteLine("unknown name")
End Select
Console.WriteLine("VB.NET is easy!")
Console.ReadKey()
End Sub
End Module
16. VB.Net - Loops
Loop in the programming language may be defined as the iteration of a
particular set of code until it meets the specified condition.VB.Net Loops is
followed by the line of statements that has to be executed recursively. It helps
in reducing the line of codes as one line of code can be executed multiple times
based on the requirement.
Types of Loops
There are five types of loops available in VB.NET:
Do While Loop
For Next Loop
For Each Loop
While End Loop
With End Loop
17. Do While Loop
In VB.NET, Do While loop is used to execute blocks of statements in the program, as
long as the condition remains true. It is similar to the While End Loop, but there is
slight difference between them. The while loop initially checks the defined condition,
if the condition becomes true, the while loop's statement is executed. Whereas in
the Do loop, is opposite of the while loop, it means that it executes the Do statements,
and then it checks the condition.
Do
[ Statements to be executed]
Loop While Boolean_expression
// or
Do
[Statement to be executed]
Loop Until Boolean_expression
18. Module Do_loop
Sub Main()
' Initializatio and Declaration of variable i
Dim i As Integer = 1
Do
' Executes the following Statement
Console.WriteLine(" Value of variable I is : {0}", i)
i = i + 1 'Increment the variable i by 1
Loop While i <= 10 ' Define the While Condition
Console.WriteLine(" Press any key to exit...")
Console.ReadKey()
End Sub
End Module
19. While... End While Loop
It executes a series of statements as long as a given condition is True.
The syntax for this loop construct is −
While condition
[ statements ]
[ Continue While ]
[ statements ]
[ Exit While ]
[ statements ]
End While
Here, statement(s) may be a single statement or a block of statements. The
condition may be any expression, and true is logical true. The loop iterates while
the condition is true.
When the condition becomes false, program control passes to the line immediately
following the loop.
20. Module loops
Sub Main()
Dim a As Integer = 10
' while loop execution '
While a < 20
Console.WriteLine("value of a: {0}", a)
a = a + 1
End While
Console.ReadLine()
End Sub
End Module
Here, key point of the While loop is that the
loop might not ever run. When the condition is
tested and the result is false, the loop body will
be skipped and the first statement after the
while loop will be executed.
21. 1. For Next Loop
For Next loop is the most frequently used loop in Vb.net. It usually checks the condition
and if it is satisfied, it lets the codes mentioned under its body execute else moves to
the next condition. It is used to perform the interaction for particular tasks for a number
of times. The next loop is available in all of the programming languages but the system
and the keywords vary.
For counter [ As datatype ] = start To end [ Step step ]
[ statements ]
[ Continue For ]
[ statements ]
[ Exit For ]
[ statements ]
Next [ counter ]
22. Module loops
Sub Main()
Dim a As Byte
' for loop execution
For a = 10 To 20
Console.WriteLine("value of a: {0}", a)
Next
Console.ReadLine()
End Sub
End Module
23. It is not exactly a looping construct. It executes a series of statements that repeatedly refers to a single object or
structure so that the statements can use a simplified syntax when accessing members of the object or structure. When
using a structure, you can only read the values of members or invoke methods, and you get an error if you try to
assign values to members of a structure used in a With...End With statement.
The syntax
With objectExpression
[ statements ]
End With
objectExpression--Required. An expression that evaluates to an object. The expression may be arbitrarily complex
and is evaluated only once. The expression can evaluate to any data type, including elementary types.
Statements--Optional. One or more statements between With and End With that may refer to members of an object
that's produced by the evaluation of objectExpression.
End With--Required. Terminates the definition of the With block.
With... End With Statement
24. Public Class Employee
' definition of global variables
Public Property name As String
Public Property age As Integer
Public Property Occupation As String
Public Property email As String
Shared Sub Main()
' Create an emp object
Dim emp As New Employee
' To define the member of an object
With emp
.name = " Mr. Stephen"
.age = 33
.Occupation = "Data Analyst"
.email = "xyz@employee.com"
End With
With emp
' use emp as a reference
Console.WriteLine(" Name is : {0}", .name)
Console.WriteLine(" Age is : {0}", .age)
Console.WriteLine(" Occupation is : {0}", .Occupation)
Console.WriteLine(" Employee Email is : {0}", .email)
End With
Console.WriteLine(" Press any key to exit...")
Console.ReadKey()
End Sub
End Class
25. Private Sub AddCustomer()
Dim theCustomer As New Customer
With theCustomer
.Name = "Coho Vineyard"
.URL = "http://www.cohovineyard.com/"
.City = "Redmond“
End With
With theCustomer.Comments
.Add("First comment.")
.Add("Second comment.")
End With
End Sub
Public Class Customer
Public Property Name As String
Public Property City As String
Public Property URL As String
Public Property Comments As New List(Of String)
End Class
26. Handling Dates and Times
Visual Basic has a number of date and time handling functions,
which appear in following Table you can even add or subtract dates using those functions.
Visual Basic date and time properties.
To do this Use this
Get the current date or time Today, Now, TimeofDay, DateString, TimeString
Perform date calculations DateAdd, DateDiff, DatePart
Return a date DateSerial, DateValue
Return a time TimeSerial, TimeValue
Set the date or time Today, TimeofDay
Time a process Timer
27. Here's an example in which 22 months added to 12/31/2001 using DateAdd.
You might note in particular that you can assign dates of the format 12/31/2001 to variables of
the Date type if you enclose them inside # symbols:
Imports System.Math
Module Module1
Sub Main()
Dim FirstDate As Date
FirstDate = #12/31/2001#
System.Console.WriteLine("New date: " & DateAdd_(DateInterval.Month, 22, FirstDate))
End Sub
End Module
Output:
New date: 10/31/2003
28. There's something else you should know-the Format function makes it easy to format
dates into strings, including times.
Using Format to display dates and times.
Format Expression Yields this
Format(Now, "M-d-yy") "1-1-03"
Format(Now, "M/d/yy") "1/1/03"
Format(Now, "MM - dd - yy") "01 /01 / 03"
Format(Now, "ddd, MMMM d, yyy") "Friday, January 1, 2003"
Format(Now, "d MMM, yyy") "1 Jan, 2003"
Format(Now, "hh:mm:ss MM/dd/yy") "01:00:00 01/01/03"
Format(Now, "hh:mm:ss tt MM-dd-yy") "01:00:00 AM 01-01-03"
29. Convering between Data type:
list of conversion functions you can use:
CBool— Convert to Bool data type.
CByte— Convert to Byte data type.
CChar— Convert to Char data type.
CDate— Convert to Date data type.
CDbl— Convert to Double data type.
CDec— Convert to Decimal data type.
CInt— Convert to Int data type.
CLng— Convert to Long data type.
CObj— Convert to Object type.
CShort— Convert to Short data type.
CSng— Convert to Single data type.
CStr— Convert to String type.
Module Module1
Sub Main()
Dim dblData As Double
Dim intData As Integer
dblData = 3.14159
intData = CInt(dblData)
System.Console.WriteLine("intData = " & Str(intData))
End Sub
End Module
30. Table: Visual Basic data conversion functions.
To convert Use this
Character code to character Chr
String to lowercase or uppercase Format, LCase, UCase, String.ToUpper, String.ToLower,
String.Format
Date to a number DateSerial, DateValue
Decimal number to other bases Hex, Oct
Number to string Format, Str
One data type to another CBool, CByte, CDate, CDbl, CDec, CInt, CLng, CObj, CSng,
CShort, CStr, Fix, Int
Character to character code Asc
String to number Val
Time to serial number TimeSerial, TimeValue
31. Arrays - declaration and manipulation
Declaring Arrays and Dynamic Arrays
An array stores a fixed-size sequential collection of elements of the same type. An array is used to store
a collection of data, but it is often more useful to think of an array as a collection of variables of the
same type.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first element
and the highest address to the last element.
To declare an array in VB.Net, you use the Dim statement. For example,
Dim (standard arrays),
Static (arrays that don't change when between calls to the procedure they're in),
Private (arrays private to the form or module they're declared in),
Protected (arrays restricted to a class or classes derived from that class),
Public (arrays global to the whole program), and more as discussed in the topic "Declaring Variables.”
32. Standard Arrays
You usually use the Dim statement to declare a standard array; here are a few examples of standard
array declarations:
Dim Data(30)
Dim Strings(10) As String
Dim TwoDArray(20, 40) As Integer
Dim Bounds(10, 100)
The Data array now has 30 elements, starting from Data(0), which is how you refer to the first
element, up to Data(29). 0 is the lower bound of this array, and 19 is the upper bound .
The Bounds array has two indices, one of which runs from 0 to 9, and the other of which runs from 0
to 99.
I can treat an array as a set of variables accessible with the array index, as here, where I'm storing a
string in Strings(3) (that is, the fourth element in the array) and then displaying that string on the
console:
Dim Data(30)
Dim Strings(10) As String
Dim TwoDArray(20, 40) As Integer
Dim Bounds(10, 100)
Strings(3) = "Here's a string!"
System.Console.WriteLine(Strings(3))
33. You can also initialize the data in an array if you don't give an array an explicit size;
here's the syntax to use, where I'm initializing an array with the values 10, 3, and 2:
Dim Data() = {10, 3, 2}
You can also initialize the array elements while declaring the array. For example,
Dim intData() As Integer = {12, 16, 20, 24, 28, 32}
Dim names() As String = {"Karthik", "Sandhya", _ "Shivangi", "Ashwitha", "Somnath"}
Dim miscData() As Object = {"Hello World", 12d, 16ui, "A"c}
34. Module arrayApl
Sub Main()
Dim n(10) As Integer ' n is an array of 11 integers
Dim i, j As Integer ' initialize elements of array n
For i = 0 To 10
n(i) = i + 100 ' set element at location i to i + 100
Next i
For j = 0 To 10
Console.WriteLine("Element({0}) = {1}", j, n(j))
Next j
Console.ReadKey()
End Sub
End Module
35. Dynamic Arrays
Dynamic arrays are arrays that can be dimensioned and re-dimensioned as par the need of the program. You can
declare a dynamic array using the ReDim statement.
Syntax for ReDim statement −
ReDim [Preserve] arrayname(subscripts)
Where,
•The Preserve keyword helps to preserve the data in an existing array, when you resize it.
•arrayname is the name of the array to re-dimension.
•subscripts specifies the new dimension.
36. Module arrayApl
Sub Main()
Dim marks() As Integer
ReDim marks(2)
marks(0) = 85
marks(1) = 75
marks(2) = 90
ReDim Preserve marks(10)
marks(3) = 80
marks(4) = 76
marks(5) = 92
marks(6) = 99
marks(7) = 79
marks(8) = 75
For i = 0 To 10
Console.WriteLine(i & vbTab & marks(i))
Next i
Console.ReadKey()
End Sub
End Module
37. Strings & string functions
Asc, AscW Returns an Integer value representing the character code corresponding to a character.
Chr, ChrW Returns the character associated with the specified character code.
Filter Returns a zero-based array containing a subset of a String array based on specified filter criteria.
Format Returns a string formatted according to instructions contained in a format String expression.
FormatCurrency Returns an expression formatted as a currency value using the currency symbol defined in the system control panel.
FormatDateTime Returns a string expression representing a date/time value.
FormatNumber Returns an expression formatted as a number.
FormatPercent Returns an expression formatted as a percentage (that is, multiplied by 100) with a trailing % character.
InStr Returns an integer specifying the start position of the first occurrence of one string within another.
InStrRev Returns the position of the first occurrence of one string within another, starting from the right side of the string.
Join Returns a string created by joining a number of substrings contained in an array.
LCase Returns a string or character converted to lowercase.
Left Returns a string containing a specified number of characters from the left side of a string.
Len Returns an integer that contains the number of characters in a string.
LSet Returns a left-aligned string containing the specified string adjusted to the specified length.
38. LTrim Returns a string containing a copy of a specified string with no leading spaces.
Mid Returns a string containing a specified number of characters from a string.
Replace Returns a string in which a specified substring has been replaced with another
substring a specified number of times.
Right Returns a string containing a specified number of characters from the right side of a
string.
RSet Returns a right-aligned string containing the specified string adjusted to the
specified length.
RTrim Returns a string containing a copy of a specified string with no trailing spaces.
Space Returns a string consisting of the specified number of spaces.
Split Returns a zero-based, one-dimensional array containing a specified number of
substrings.
StrComp Returns -1, 0, or 1, based on the result of a string comparison.
StrConv Returns a string converted as specified.
StrDup Returns a string or object consisting of the specified character repeated the
specified number of times.
StrReverse Returns a string in which the character order of a specified string is reversed.
Trim Returns a string containing a copy of a specified string with no leading or trailing
spaces.
UCase Returns a string or character containing the specified string converted to uppercase.