SlideShare a Scribd company logo
1 of 39
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
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
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
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.
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
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
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
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
The following diagram represents the functioning of the If-Else-If Statement in the VB.NET
programming language.
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
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
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
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
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
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
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
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
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.
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.
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 ]
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
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
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
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
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
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
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"
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
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
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.”
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))
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}
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
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.
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
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.
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.
Thank You

More Related Content

What's hot

Vb decision making statements
Vb decision making statementsVb decision making statements
Vb decision making statementspragya ratan
 
Control Structures in Visual Basic
Control Structures in  Visual BasicControl Structures in  Visual Basic
Control Structures in Visual BasicTushar Jain
 
Chapter 4(1)
Chapter 4(1)Chapter 4(1)
Chapter 4(1)TejaswiB4
 
Control Statements in Java
Control Statements in JavaControl Statements in Java
Control Statements in JavaNiloy Saha
 
itft-Decision making and branching in java
itft-Decision making and branching in javaitft-Decision making and branching in java
itft-Decision making and branching in javaAtul Sehdev
 
Conditional statement
Conditional statementConditional statement
Conditional statementMaxie Santos
 
Decision statements in vb.net
Decision statements in vb.netDecision statements in vb.net
Decision statements in vb.netilakkiya
 
Conditional statements
Conditional statementsConditional statements
Conditional statementscherrybear2014
 
Bt0067 c programming and data structures 1
Bt0067 c programming and data structures 1Bt0067 c programming and data structures 1
Bt0067 c programming and data structures 1Techglyphs
 
Selection statements
Selection statementsSelection statements
Selection statementsHarsh Dabas
 
OCA JAVA - 2 Programming with Java Statements
 OCA JAVA - 2 Programming with Java Statements OCA JAVA - 2 Programming with Java Statements
OCA JAVA - 2 Programming with Java StatementsFernando Gil
 
Control statements in Java
Control statements  in JavaControl statements  in Java
Control statements in JavaJin Castor
 
Conditional statement in c
Conditional statement in cConditional statement in c
Conditional statement in cMuthuganesh S
 
10. switch case
10. switch case10. switch case
10. switch caseWay2itech
 
Control structures in Java
Control structures in JavaControl structures in Java
Control structures in JavaRavi_Kant_Sahu
 
Cse lecture-6-c control statement
Cse lecture-6-c control statementCse lecture-6-c control statement
Cse lecture-6-c control statementFarshidKhan
 

What's hot (20)

Vb decision making statements
Vb decision making statementsVb decision making statements
Vb decision making statements
 
Control Structures in Visual Basic
Control Structures in  Visual BasicControl Structures in  Visual Basic
Control Structures in Visual Basic
 
Chapter 4(1)
Chapter 4(1)Chapter 4(1)
Chapter 4(1)
 
Control Statements in Java
Control Statements in JavaControl Statements in Java
Control Statements in Java
 
itft-Decision making and branching in java
itft-Decision making and branching in javaitft-Decision making and branching in java
itft-Decision making and branching in java
 
Conditional statement
Conditional statementConditional statement
Conditional statement
 
Decision statements in vb.net
Decision statements in vb.netDecision statements in vb.net
Decision statements in vb.net
 
Conditional statements
Conditional statementsConditional statements
Conditional statements
 
Bt0067 c programming and data structures 1
Bt0067 c programming and data structures 1Bt0067 c programming and data structures 1
Bt0067 c programming and data structures 1
 
Selection statements
Selection statementsSelection statements
Selection statements
 
Flow Control (C#)
Flow Control (C#)Flow Control (C#)
Flow Control (C#)
 
OCA JAVA - 2 Programming with Java Statements
 OCA JAVA - 2 Programming with Java Statements OCA JAVA - 2 Programming with Java Statements
OCA JAVA - 2 Programming with Java Statements
 
Control statements in Java
Control statements  in JavaControl statements  in Java
Control statements in Java
 
Computer programming 2 Lesson 9
Computer programming 2  Lesson 9Computer programming 2  Lesson 9
Computer programming 2 Lesson 9
 
Computer programming 2 - Lesson 7
Computer programming 2 - Lesson 7Computer programming 2 - Lesson 7
Computer programming 2 - Lesson 7
 
Decisions
DecisionsDecisions
Decisions
 
Conditional statement in c
Conditional statement in cConditional statement in c
Conditional statement in c
 
10. switch case
10. switch case10. switch case
10. switch case
 
Control structures in Java
Control structures in JavaControl structures in Java
Control structures in Java
 
Cse lecture-6-c control statement
Cse lecture-6-c control statementCse lecture-6-c control statement
Cse lecture-6-c control statement
 

Similar to BSc. III Unit iii VB.NET

Unit IV Array in VB.Net.pptx
Unit IV Array in VB.Net.pptxUnit IV Array in VB.Net.pptx
Unit IV Array in VB.Net.pptxUjwala Junghare
 
Chapter 2 - Flow of Control Part I.pdf
Chapter 2 -  Flow of Control Part I.pdfChapter 2 -  Flow of Control Part I.pdf
Chapter 2 - Flow of Control Part I.pdfKirubelWondwoson1
 
Flow of control by deepak lakhlan
Flow of control by deepak lakhlanFlow of control by deepak lakhlan
Flow of control by deepak lakhlanDeepak Lakhlan
 
web presentation 138.pptx
web presentation 138.pptxweb presentation 138.pptx
web presentation 138.pptxAbhiYadav655132
 
Conditional Statements & Loops
Conditional Statements & LoopsConditional Statements & Loops
Conditional Statements & Loopssimmis5
 
Java Decision Control
Java Decision ControlJava Decision Control
Java Decision ControlJayfee Ramos
 
Learn C# Programming - Decision Making & Loops
Learn C# Programming - Decision Making & LoopsLearn C# Programming - Decision Making & Loops
Learn C# Programming - Decision Making & LoopsEng Teong Cheah
 
Creating decision structures of a program
Creating decision structures of a programCreating decision structures of a program
Creating decision structures of a programYsa Castillo
 
Do While Repetition Structure
Do While Repetition StructureDo While Repetition Structure
Do While Repetition StructureShahzu2
 
Control statements
Control statementsControl statements
Control statementsCutyChhaya
 
Control structures
Control structuresControl structures
Control structuresGehad Enayat
 
CONTROL STRUCTURE IN VB
CONTROL STRUCTURE IN VBCONTROL STRUCTURE IN VB
CONTROL STRUCTURE IN VBclassall
 
Flow of control C ++ By TANUJ
Flow of control C ++ By TANUJFlow of control C ++ By TANUJ
Flow of control C ++ By TANUJTANUJ ⠀
 
Introduction To Programming with Python Lecture 2
Introduction To Programming with Python Lecture 2Introduction To Programming with Python Lecture 2
Introduction To Programming with Python Lecture 2Syed Farjad Zia Zaidi
 

Similar to BSc. III Unit iii VB.NET (20)

Unit IV Array in VB.Net.pptx
Unit IV Array in VB.Net.pptxUnit IV Array in VB.Net.pptx
Unit IV Array in VB.Net.pptx
 
Control statements in java
Control statements in javaControl statements in java
Control statements in java
 
Chapter 2 - Flow of Control Part I.pdf
Chapter 2 -  Flow of Control Part I.pdfChapter 2 -  Flow of Control Part I.pdf
Chapter 2 - Flow of Control Part I.pdf
 
Flow of control by deepak lakhlan
Flow of control by deepak lakhlanFlow of control by deepak lakhlan
Flow of control by deepak lakhlan
 
web presentation 138.pptx
web presentation 138.pptxweb presentation 138.pptx
web presentation 138.pptx
 
Conditional Statements & Loops
Conditional Statements & LoopsConditional Statements & Loops
Conditional Statements & Loops
 
Java Decision Control
Java Decision ControlJava Decision Control
Java Decision Control
 
Learn C# Programming - Decision Making & Loops
Learn C# Programming - Decision Making & LoopsLearn C# Programming - Decision Making & Loops
Learn C# Programming - Decision Making & Loops
 
Creating decision structures of a program
Creating decision structures of a programCreating decision structures of a program
Creating decision structures of a program
 
Comp ppt (1)
Comp ppt (1)Comp ppt (1)
Comp ppt (1)
 
Decision making and branching
Decision making and branchingDecision making and branching
Decision making and branching
 
Do While Repetition Structure
Do While Repetition StructureDo While Repetition Structure
Do While Repetition Structure
 
C sharp chap4
C sharp chap4C sharp chap4
C sharp chap4
 
6.pptx
6.pptx6.pptx
6.pptx
 
Controls & Loops in C
Controls & Loops in C Controls & Loops in C
Controls & Loops in C
 
Control statements
Control statementsControl statements
Control statements
 
Control structures
Control structuresControl structures
Control structures
 
CONTROL STRUCTURE IN VB
CONTROL STRUCTURE IN VBCONTROL STRUCTURE IN VB
CONTROL STRUCTURE IN VB
 
Flow of control C ++ By TANUJ
Flow of control C ++ By TANUJFlow of control C ++ By TANUJ
Flow of control C ++ By TANUJ
 
Introduction To Programming with Python Lecture 2
Introduction To Programming with Python Lecture 2Introduction To Programming with Python Lecture 2
Introduction To Programming with Python Lecture 2
 

Recently uploaded

Analytical Profile of Coleus Forskohlii | Forskolin .pdf
Analytical Profile of Coleus Forskohlii | Forskolin .pdfAnalytical Profile of Coleus Forskohlii | Forskolin .pdf
Analytical Profile of Coleus Forskohlii | Forskolin .pdfSwapnil Therkar
 
Discovery of an Accretion Streamer and a Slow Wide-angle Outflow around FUOri...
Discovery of an Accretion Streamer and a Slow Wide-angle Outflow around FUOri...Discovery of an Accretion Streamer and a Slow Wide-angle Outflow around FUOri...
Discovery of an Accretion Streamer and a Slow Wide-angle Outflow around FUOri...Sérgio Sacani
 
STERILITY TESTING OF PHARMACEUTICALS ppt by DR.C.P.PRINCE
STERILITY TESTING OF PHARMACEUTICALS ppt by DR.C.P.PRINCESTERILITY TESTING OF PHARMACEUTICALS ppt by DR.C.P.PRINCE
STERILITY TESTING OF PHARMACEUTICALS ppt by DR.C.P.PRINCEPRINCE C P
 
Call Girls in Mayapuri Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Mayapuri Delhi 💯Call Us 🔝9953322196🔝 💯Escort.Call Girls in Mayapuri Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Mayapuri Delhi 💯Call Us 🔝9953322196🔝 💯Escort.aasikanpl
 
Call Us ≽ 9953322196 ≼ Call Girls In Mukherjee Nagar(Delhi) |
Call Us ≽ 9953322196 ≼ Call Girls In Mukherjee Nagar(Delhi) |Call Us ≽ 9953322196 ≼ Call Girls In Mukherjee Nagar(Delhi) |
Call Us ≽ 9953322196 ≼ Call Girls In Mukherjee Nagar(Delhi) |aasikanpl
 
Labelling Requirements and Label Claims for Dietary Supplements and Recommend...
Labelling Requirements and Label Claims for Dietary Supplements and Recommend...Labelling Requirements and Label Claims for Dietary Supplements and Recommend...
Labelling Requirements and Label Claims for Dietary Supplements and Recommend...Lokesh Kothari
 
Traditional Agroforestry System in India- Shifting Cultivation, Taungya, Home...
Traditional Agroforestry System in India- Shifting Cultivation, Taungya, Home...Traditional Agroforestry System in India- Shifting Cultivation, Taungya, Home...
Traditional Agroforestry System in India- Shifting Cultivation, Taungya, Home...jana861314
 
Biopesticide (2).pptx .This slides helps to know the different types of biop...
Biopesticide (2).pptx  .This slides helps to know the different types of biop...Biopesticide (2).pptx  .This slides helps to know the different types of biop...
Biopesticide (2).pptx .This slides helps to know the different types of biop...RohitNehra6
 
Nanoparticles synthesis and characterization​ ​
Nanoparticles synthesis and characterization​  ​Nanoparticles synthesis and characterization​  ​
Nanoparticles synthesis and characterization​ ​kaibalyasahoo82800
 
Stunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCR
Stunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCRStunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCR
Stunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCRDelhi Call girls
 
Nightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43b
Nightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43bNightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43b
Nightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43bSérgio Sacani
 
All-domain Anomaly Resolution Office U.S. Department of Defense (U) Case: “Eg...
All-domain Anomaly Resolution Office U.S. Department of Defense (U) Case: “Eg...All-domain Anomaly Resolution Office U.S. Department of Defense (U) Case: “Eg...
All-domain Anomaly Resolution Office U.S. Department of Defense (U) Case: “Eg...Sérgio Sacani
 
Bentham & Hooker's Classification. along with the merits and demerits of the ...
Bentham & Hooker's Classification. along with the merits and demerits of the ...Bentham & Hooker's Classification. along with the merits and demerits of the ...
Bentham & Hooker's Classification. along with the merits and demerits of the ...Nistarini College, Purulia (W.B) India
 
Hubble Asteroid Hunter III. Physical properties of newly found asteroids
Hubble Asteroid Hunter III. Physical properties of newly found asteroidsHubble Asteroid Hunter III. Physical properties of newly found asteroids
Hubble Asteroid Hunter III. Physical properties of newly found asteroidsSérgio Sacani
 
Lucknow 💋 Russian Call Girls Lucknow Finest Escorts Service 8923113531 Availa...
Lucknow 💋 Russian Call Girls Lucknow Finest Escorts Service 8923113531 Availa...Lucknow 💋 Russian Call Girls Lucknow Finest Escorts Service 8923113531 Availa...
Lucknow 💋 Russian Call Girls Lucknow Finest Escorts Service 8923113531 Availa...anilsa9823
 
Physiochemical properties of nanomaterials and its nanotoxicity.pptx
Physiochemical properties of nanomaterials and its nanotoxicity.pptxPhysiochemical properties of nanomaterials and its nanotoxicity.pptx
Physiochemical properties of nanomaterials and its nanotoxicity.pptxAArockiyaNisha
 
Disentangling the origin of chemical differences using GHOST
Disentangling the origin of chemical differences using GHOSTDisentangling the origin of chemical differences using GHOST
Disentangling the origin of chemical differences using GHOSTSérgio Sacani
 
Isotopic evidence of long-lived volcanism on Io
Isotopic evidence of long-lived volcanism on IoIsotopic evidence of long-lived volcanism on Io
Isotopic evidence of long-lived volcanism on IoSérgio Sacani
 
A relative description on Sonoporation.pdf
A relative description on Sonoporation.pdfA relative description on Sonoporation.pdf
A relative description on Sonoporation.pdfnehabiju2046
 
Botany 4th semester file By Sumit Kumar yadav.pdf
Botany 4th semester file By Sumit Kumar yadav.pdfBotany 4th semester file By Sumit Kumar yadav.pdf
Botany 4th semester file By Sumit Kumar yadav.pdfSumit Kumar yadav
 

Recently uploaded (20)

Analytical Profile of Coleus Forskohlii | Forskolin .pdf
Analytical Profile of Coleus Forskohlii | Forskolin .pdfAnalytical Profile of Coleus Forskohlii | Forskolin .pdf
Analytical Profile of Coleus Forskohlii | Forskolin .pdf
 
Discovery of an Accretion Streamer and a Slow Wide-angle Outflow around FUOri...
Discovery of an Accretion Streamer and a Slow Wide-angle Outflow around FUOri...Discovery of an Accretion Streamer and a Slow Wide-angle Outflow around FUOri...
Discovery of an Accretion Streamer and a Slow Wide-angle Outflow around FUOri...
 
STERILITY TESTING OF PHARMACEUTICALS ppt by DR.C.P.PRINCE
STERILITY TESTING OF PHARMACEUTICALS ppt by DR.C.P.PRINCESTERILITY TESTING OF PHARMACEUTICALS ppt by DR.C.P.PRINCE
STERILITY TESTING OF PHARMACEUTICALS ppt by DR.C.P.PRINCE
 
Call Girls in Mayapuri Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Mayapuri Delhi 💯Call Us 🔝9953322196🔝 💯Escort.Call Girls in Mayapuri Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
Call Girls in Mayapuri Delhi 💯Call Us 🔝9953322196🔝 💯Escort.
 
Call Us ≽ 9953322196 ≼ Call Girls In Mukherjee Nagar(Delhi) |
Call Us ≽ 9953322196 ≼ Call Girls In Mukherjee Nagar(Delhi) |Call Us ≽ 9953322196 ≼ Call Girls In Mukherjee Nagar(Delhi) |
Call Us ≽ 9953322196 ≼ Call Girls In Mukherjee Nagar(Delhi) |
 
Labelling Requirements and Label Claims for Dietary Supplements and Recommend...
Labelling Requirements and Label Claims for Dietary Supplements and Recommend...Labelling Requirements and Label Claims for Dietary Supplements and Recommend...
Labelling Requirements and Label Claims for Dietary Supplements and Recommend...
 
Traditional Agroforestry System in India- Shifting Cultivation, Taungya, Home...
Traditional Agroforestry System in India- Shifting Cultivation, Taungya, Home...Traditional Agroforestry System in India- Shifting Cultivation, Taungya, Home...
Traditional Agroforestry System in India- Shifting Cultivation, Taungya, Home...
 
Biopesticide (2).pptx .This slides helps to know the different types of biop...
Biopesticide (2).pptx  .This slides helps to know the different types of biop...Biopesticide (2).pptx  .This slides helps to know the different types of biop...
Biopesticide (2).pptx .This slides helps to know the different types of biop...
 
Nanoparticles synthesis and characterization​ ​
Nanoparticles synthesis and characterization​  ​Nanoparticles synthesis and characterization​  ​
Nanoparticles synthesis and characterization​ ​
 
Stunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCR
Stunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCRStunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCR
Stunning ➥8448380779▻ Call Girls In Panchshil Enclave Delhi NCR
 
Nightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43b
Nightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43bNightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43b
Nightside clouds and disequilibrium chemistry on the hot Jupiter WASP-43b
 
All-domain Anomaly Resolution Office U.S. Department of Defense (U) Case: “Eg...
All-domain Anomaly Resolution Office U.S. Department of Defense (U) Case: “Eg...All-domain Anomaly Resolution Office U.S. Department of Defense (U) Case: “Eg...
All-domain Anomaly Resolution Office U.S. Department of Defense (U) Case: “Eg...
 
Bentham & Hooker's Classification. along with the merits and demerits of the ...
Bentham & Hooker's Classification. along with the merits and demerits of the ...Bentham & Hooker's Classification. along with the merits and demerits of the ...
Bentham & Hooker's Classification. along with the merits and demerits of the ...
 
Hubble Asteroid Hunter III. Physical properties of newly found asteroids
Hubble Asteroid Hunter III. Physical properties of newly found asteroidsHubble Asteroid Hunter III. Physical properties of newly found asteroids
Hubble Asteroid Hunter III. Physical properties of newly found asteroids
 
Lucknow 💋 Russian Call Girls Lucknow Finest Escorts Service 8923113531 Availa...
Lucknow 💋 Russian Call Girls Lucknow Finest Escorts Service 8923113531 Availa...Lucknow 💋 Russian Call Girls Lucknow Finest Escorts Service 8923113531 Availa...
Lucknow 💋 Russian Call Girls Lucknow Finest Escorts Service 8923113531 Availa...
 
Physiochemical properties of nanomaterials and its nanotoxicity.pptx
Physiochemical properties of nanomaterials and its nanotoxicity.pptxPhysiochemical properties of nanomaterials and its nanotoxicity.pptx
Physiochemical properties of nanomaterials and its nanotoxicity.pptx
 
Disentangling the origin of chemical differences using GHOST
Disentangling the origin of chemical differences using GHOSTDisentangling the origin of chemical differences using GHOST
Disentangling the origin of chemical differences using GHOST
 
Isotopic evidence of long-lived volcanism on Io
Isotopic evidence of long-lived volcanism on IoIsotopic evidence of long-lived volcanism on Io
Isotopic evidence of long-lived volcanism on Io
 
A relative description on Sonoporation.pdf
A relative description on Sonoporation.pdfA relative description on Sonoporation.pdf
A relative description on Sonoporation.pdf
 
Botany 4th semester file By Sumit Kumar yadav.pdf
Botany 4th semester file By Sumit Kumar yadav.pdfBotany 4th semester file By Sumit Kumar yadav.pdf
Botany 4th semester file By Sumit Kumar yadav.pdf
 

BSc. III Unit iii VB.NET

  • 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.