0% found this document useful (0 votes)
6 views

Chapter 3

Uploaded by

Hayome Takele
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Chapter 3

Uploaded by

Hayome Takele
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 122

CHAPTER 3

object oriented fundamentals in vb.net


SYNTAX AND SEMANTICS

• Syntax of programming languages tells us how a program looks like


• Semantics tells us what the program means.

1. Statements

• Visual Basic programs contain a basic building block named a statement.


• A statement could be an instruction or combination of instructions.
• As a rule, each Visual Basic statement is supposed to be written in one
line and no termination is actually required.
• Successive Visual Basic statements are thus written downwards with each
instruction beginning on a new line.
SYNTAX AND SEMANTICS…
• Some Visual Basic statement becomes too long to be written on a single line.
• We will use the underscore sign (_) to inform to the VB Editor that the
instruction is continued to next line.
• The underscore sign is called a continuation character.
A Visual Basic Program
Statement1
Statement2
Statement3
A very long statement _
which requires more than one line
• The first three statements are very short and are written on a single line while
the last instruction is written on two lines and an underscore character has been
used.
SYNTAX AND SEMANTICS…
• Sometimes, we may even want to write more than one VB
statements in a line, and there is no statement terminator in VB.
• You can place two or more statements on a line if you use a
colon (:) to separate them
Statement1 : Statement1 : Statement1 = _
Statement3
• Example:
Dim x as integer, y as integer, z as integer
x=y + z : y=z + 10
• In order to make your code more readable, however, it's better to
place each statement on a separate line!
SYNTAX AND SEMANTICS…
Naming Convention
• In Visual Basic code, you declare and name many elements (Sub and
Function procedures, variables, constants, etc).
• The names of the procedures, variables, and constants that you
declare in your Visual Basic code must follow these guidelines:
• They must begin with a letter.
• They can't contain type-declaration characters (special characters that
specify a data type).
• They can be no longer than 255 characters.
• The names of controls, forms, classes, and modules must not exceed 40
characters.
• They can't be the same as restricted keywords (If, loop, case, …).
1. COMMENTS

• In Visual Basic program, the comment symbol is ‘(apostrophe).

• This symbol tells Visual Basic to ignore the words that follow it.

• Comments are placed in the code for the benefit of the developer, and other

programmers who might examine the code later.

• For example:

' This is a comment beginning at the left edge of the screen.Text1.Text = "Hi!" '

Place friendly greeting in text box.

• Comments can follow a statement on the same line or can occupy an entire line.

• Remember that comments can't follow a line-continuation character on the same

line.
2. VARIABLES
• Visual Basic uses variables for storing values.
• Variables have a name and a data type which determines the kind
of data the variable can store.

Variable Declaration
• Before we use a variable in Visual Basic code, we have to declare
it.
• To declare a variable is to tell the program about it in advance.
• You declare a variable with the Dim statement, supplying a name
for the variable.

• Syntax:
[accessibility] [Shared] [Dim] name [As type] [= initial value]
2. VARIABLES…
• A variable name:
• Must begin with a letter.
• Can't contain type-declaration character.
• Must not exceed 255 characters.
• Must be unique within the same scope, which is the range from
which the variable can be referenced — a procedure, a form, and
so on.

• The optional As type clause in the Dim statement allows you to


define the data type of the variable you are declaring.
2. VARIABLES…
Accessibility
• A variable declaration’s accessibility clause can take one of the following
values:
• Public — you can use the Public keyword only for variables declared at
the module, class, structure, namespace, or file level but not inside a
subroutine.
• Public indicates that the variable should be available to all code inside or
outside of the variable’s module.
• Protected — you can use the Protected keyword only at the class level,
not inside a module or inside a routine within a class.
• Protected indicates that the variable should be accessible only to code
within the same class or a derived class.
• Friend — you can use the Friend keyword only for variables declared at
the module, class, namespace, or file level, not inside a subroutine.
• Friend indicates that the variable should be available to all code inside or
outside of the variable’s module within the same project.
2. VARIABLES…
• Protected Friend — you can use Protected Friend only at the class level,
not inside a module or inside a routine within a class.
• A variable declared Protected Friend is accessible only to code within
the same class or a derived class and only within the same project.
• Private — you can use the Private keyword only for variables declared
at the module, class, or structure, not inside a subroutine.
• A variable declared Private is accessible only to code in the same
module, class, or structure.
• Static — you can use the Static keyword only for variables declared
within a subroutine or a block within a subroutine.
• A variable declared Static keeps its value between lifetimes.
• For example, if a subroutine sets a Static variable to 27 before it exits,
the variable begins with the value 27 the next time the subroutine
executes.
2. VARIABLES…
Dim
• The Dim keyword tells VB that you want to create a variable.
• You can omit the Dim keyword if you specify Public, Protected, Friend,
Protected Friend, Private or Static.
• If you do not specify otherwise, variables you declare using a Dim
statement are Private.
• The following two statements are equivalent:
Dim num_people As Integer
Private num_people As Integer

• One place where the Dim keyword is common is when declaring


variables inside subroutines.
• You cannot use the Private, Public, Protected, Friend, Protected Friend,
for that matter inside subroutines, so you must use either Static or
Dim.
3. DATA TYPES

• The data type of a variable determines what values are stored in


the computer's memory.

• When you declare a variable, you can also supply a data type for
it.

• All variables have a data type that determines what kind of data
they can store.

• In fact, just about anything in Visual Basic that involves data also
involves data types.
Type Size Values
Boolean 2 bytes True or False
Byte 1 byte 0 to 255 (unsigned byte)
SByte 1 byte -128 to 127 (signed byte)
Char 2 bytes 0 to 65,535 (unsigned character)
Short 2 bytes -32,768 to 32,767
UShort 2 bytes 0 through 65,535 (unsigned short)
Integer 4 bytes -2,147,483,648 to 2,147,483,647
UInteger 4 bytes 0 through 4,294,967,295 (unsigned integer)
Long 8 bytes -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
ULong 8 bytes 0 through 18,446,744,073,709,551,615 (unsigned long)

0 to +/−79,228,162,514,264,337,593,543,950,335 with n decimal point. 0 to


Decimal 16 bytes
+/−7.9228162514264337593543950335 with 28 places
−3.4028235E+ 38 to −1.401298E- 45 (negative values)
Single 4 bytes
1.401298E – 45 to 3.4028235E + 38 (positive values)
−1.79769313486231570E+308 to
Double 8 bytes −4.94065645841246544E – 324 (negative values)
4.94065645841246544E - 324 to 1.79769313486231570E + 308 (positive values)
Depending on the platform, a string can hold approximately 0 to 2 billion Unicode
String variable
characters
Date 8 bytes January 1, 0001 0:0:00 to December 31, 9999 11:59:59 pm
Object 4 bytes Any type can be stored in a variable of type Object
Structure variable Structure members have their own ranges
3. DATA TYPES…
• Before using a variable, you must use the Private, Public, Dim or
Static statement to declare it.
• For example, the following statements declare an Integer, Double,
String, and Double type, respectively:
Private I As Integer
Dim Amt As Double
StaticYourName As String
Public BillsPaid As Double

• A Declaration statement can combine multiple declarations:


Private I As Integer, Amt As Double
PrivateYourName As String, BillsPaid As Double
Private Test Double,Amount As Double, J As Integer
3. DATA TYPES…
Numeric Data Types
• Visual Basic supplies several numeric data types:
• Short,
• Integer,
• Long (long integer),
• Single (single-precision floating point),
• Double (double-precision floating point), and
• Decimal.

• If you know that a variable will always store whole numbers rather than
numbers with a fractional amount, declare it as Short, Integer or Long
type.
• If the variable contains a fraction, declare it as a Single, Double, or
Decimal variable.
3. DATA TYPES…
The Byte Data Type

• In some situations, data is stored as bytes, and you want to access


individual bytes.
• The Byte type holds an integer in the range 0 to 255.
• Bytes are frequently used to access binary files, image and sound files,
and so on.
• Since Byte is an unsigned type, it cannot represent a negative number.
Dim A As Byte, B As Byte
A = 233
B = 50
• But the following statement will produce an overflow exception:
B =A + B
• The result (283) can’t be stored in a single byte.
3. DATA TYPES…
The String Data Type
• If you have a variable that always contains a string and never a
numeric value, you can declare it to be of type String:
Private S As String
• You can then assign strings to this variable and manipulate it using
string functions:
S = "Database"
• You can store nearly 2GB (2 billion characters) of text in a string
variable.
• Each code point, or character code, represents a single Unicode
character.
• So it allows you to work with any language in the world.
3. DATA TYPES…
• Once you assign a string to a String variable, that string
is immutable, meaning you cannot change its length or contents.
• When you alter a string in any way, Visual Basic creates a new
string and abandons the previous one.
• The String variable then points to the new string.
• You must enclose a String literal within quotation marks (" ").
• To include a quotation mark as one of the characters in the string,
use two contiguous quotation marks ("").
• The following example illustrates this:
Dim h As String = "Hello“
Dim j As String = "Joe said ""Hello"" to me."
3. DATA TYPES…
Boolean Data Type
• If you have a variable that will contain simple true/false, yes/no, or on/off
information, you can declare it to be of type Boolean.
• The default value of Boolean is False.
• In the following example, blnRunning is a Boolean variable which stores a simple
yes/no setting.
Dim blnRunning As Boolean
‘ Check to see if the tape is running.
If Recorder.Direction = 1 Then
blnRunning = True
End if
• Boolean Type Conversions
• When converting numeric data type values to Boolean, 0 becomes False and all
other values become True.
• When converting Boolean values to numeric types, False becomes 0
and True becomes -1.
3. DATA TYPES…
Date Data Type
• Date and time values can be contained in Date data type variables.
• Date holds 8-byte values that represent dates ranging from January
1 of the year 0001 through December 31 of the year 9999, and
times from 12:00:00 AM (midnight) through 11:59:59.9999999 PM.
• Each increment represents 100 nanoseconds of elapsed time since
the beginning of January 1 of the year 1 in the Gregorian calendar.
• Use the Date data type to contain date values, time values, or date
and time values.
• The default value of Date is 0:00:00 (midnight) on January 1, 0001.
• You must enclose a Date literal within number signs (# #).
• You must specify the date value in the format M/d/yyyy, for
example #5/31/1993#.
3. DATA TYPES…
Dim expiration As Date
• The following are all valid assignments:
expiration = #01/01/2004#
expiration = #8/27/2001 6:29:11 PM#
expiration = “July 2, 2002”
expiration = Now()
• The Now() function returns the current system date and time.
• They are double-precision numbers: the integer part represents the
date and the fractional part represents the time.
• When other numeric data types are converted to Date, values to the
left of the decimal represent date information, while values to the right
of the decimal represent time.
• Midnight is 0, and midday is 0.5.
• Negative whole numbers represent dates before December 30, 1899.
3. DATA TYPES…
Data Type Conversion
• Sometimes, you will need to convert variables from one type into
another.
• A narrowing conversion - data is converted from one type to another
that cannot hold all of the possible values allowed by the original data
type.
• For example, a Long value can hold values that are too big to fit in an
Integer, so this is a narrowing conversion.
• The value contained in the Long variable may or may not fit in the
Integer.
Dim an_integer As Integer
Dim a_long As Long
...
an_integer = a_long
3. DATA TYPES…

• A widening conversion - a widening conversion is one where the new data


type is always big enough to hold the old data type’s values.

• A typical example of a widening conversion is converting from


an Integer into a Double as in the following lines of code:

'Widening conversion

Dim i As Integer = 1

Dim d As Double = i

• Visual Basic allows widening conversions.


3. DATA TYPES…
Function Converts To
CBool(value) Converts value to Boolean
CByte(value) Converts value to Byte
CChar(value) Converts value to Unicode character
CDate(value) Converts value to Date
CDbl(value) Converts value to Double
CDec(value) Converts value to Decimal
CInt (value) Converts value to Integer (4-byte integer, Int32)
CLng(value) Converts value to Long (8-byte integer, Int64)
CObj (value) Converts value to Object
CShort(value) Converts value to Short (2-byte integer, Int16)
CSng(value) Converts value to Single
CStr(value) Converts value to String
CSByte(value) Converts value to SByte
CUInt(value) Converts value to UInteger
CULng(value) Converts value to ULong
CUShort(value) Converts value to UShort
3. DATA TYPES…
• Example
Dim A As Integer
A = 10
Dim B As Double
B = CDbl(A)
• The CInt and CLng functions round fractional values off to the nearest
whole number.
• If the fractional part of a number is exactly .5, the functions round to
the nearest even whole number.
• For example, 0.5 rounds to 0, 0.6 rounds to 1.

• In contrast, the Fix and Int functions truncate fractional values.


• Fix truncates toward zero, so Fix(-0.9) is 0 and Fix(0.9) is 0 .
• Int truncates downward, so Int(-0.9) is -1 and Int(0.9) is 0 .
3. DATA TYPES…
• You can also use the CType() function to convert a variable or
expression from one data type to another.
• The CType function takes a value and data type as parameters, and it
converts the value into that type if possible.

• The following statement converts the value of the A variable to a


Decimal value and uses it in a calculation:
Dim a As Double = 23.8
Dim b As Integer
b = CType(a, Integer)
• When the Strict option is On, VB.NET will perform conversions that do
not result in loss of accuracy (precision) or magnitude.
• These conversions are called widening conversions, as opposed to the
narrowing conversions.
3. DATA TYPES…
Type Declaration Characters
• We can also specify the data type of a variable using suffix.
• Suffix is a character that represents a certain data type.
• They can be used as implicit declaration to specify data type of a
variable during declaration.

Symbol Data Type Example


$ String A$, messageText$
% Integer (Int32) counter%, var%
& Long (Int64) population&, colorValue&
! Single distance!
# Double ExactDistance#
@ Decimal Balance@
3. DATA TYPES…
• Example:
Dim age as Integer
Dim price as Decimal
• This could be declared using suffixes as:
Dim age%
Dim price@
• After declaration, you can drop or still use the suffix when
accessing the variable declared using suffixes.

• The following is possible:


Dim age%
age = 100
Console.write (age%)
4. CONSTANTS

• Constants are similar to variables.


• The main difference is that the value contained in memory cannot
be changed once the constant is declared.
• You can't modify a constant or assign a new value to it.

• The syntax for declaring a constant is:


[Public|Private] Const constantname[As type] = expression
• A Const statement can represent a mathematical or date/time
quantity:
Const conPI = 3.14159265358979
Public Const conMaxPlanets As Integer = 9
Const conReleaseDate = #1/1/95#
SCOPE AND LIFE TIME OF VARIABLES

• The scope of a variable defines which parts of your code are aware of its
existence.

• When you declare a variable within a procedure, only code within that
procedure can access or change the value of that variable

• It has a scope that is local to that procedure.

• Sometimes, however, you need to use a variable with a broader scope, such as
one whose value is available to all the procedures within the same module, or
even to all the procedures in your entire application.

• Visual Basic allows you to specify the scope of a variable when you declare it.
SCOPE AND LIFE TIME OF VARIABLES…

Scope Private Public

Procedure-level Variables are private to the Not applicable. You cannot


procedure in which they appear. declare public variables within
a procedure.

Module-level Variables are private to the Variables are available to all


module in which they appear. modules.
SCOPE AND LIFE TIME OF VARIABLES…

Variables Used Within a Procedure


• Procedure-level variables are recognized only in the procedure in
which they're declared.
• These are also known as local variables.
• You declare them with the Dim or Static keywords.
• For example:
Sub adder()
Dim intTemp As Integer
Static intPermanent As Integer
...
End sub
• Values in local variables declared with Static exist the entire time your
application is running while variables declared with Dim exist only as
long as the procedure is executing.
SCOPE AND LIFE TIME OF VARIABLES…

Variables Used Within a Module


• A module-level variable is available to all the procedures in that
module, but not to code in other modules.
• You create module-level variables by declaring them with the Private
keyword in the Declarations section.
• For example:
Private intTemp As Integer
• At the module level, there is no difference between Private and Dim.

Variables Used by All Modules


• To make a module-level variable publicly available, use the Public
keyword to declare the variable.
• The values in public variables are available to all procedures in your
application.
Public intTemp As Integer
OPTION STATEMENTS
• There are three Option statements, which affect the behavior of the
compiler.
• If used, they must appear before any declarations in the same source
file.
• They control the compilation of the source code in the file in which
they appear.

Option Compare
• The Option Compare statement controls the manner in which strings
are compared to each other.The syntax is:
Option Compare [ Binary | Text ]
• If Binary is specified, strings are compared based on their internal
binary representation (i.e., string comparisons are case-sensitive).
• If Text is specified, strings are compared based on case-insensitive
alphabetical order.
• The default is Binary.
OPTION STATEMENTS…
Option Explicit
• The Option Explicit statement determines whether the compiler
requires all variables to be explicitly declared.
• The syntax is:
Option Explicit [ On | Off ]
• If On is specified, the compiler requires all variables to be
declared.
• If Off is specified, the compiler considers a variable's use to be an
implicit declaration.
• It is considered good programming practice to require declaration
of variables.
• The default is On.
OPTION STATEMENTS…
Option Strict
• The Option Strict statement controls the implicit type conversions that
the compiler will allow.
• The syntax is:
Option Strict [ On | Off ]
• If On is specified, the compiler only allows implicit widening conversions;
narrowing conversions must be explicit.
• If Off is specified, the compiler allows implicit narrowing conversions as
well.
• The default is Off.
• narrowing conversion is not always safe since the source data will
sometimes fail to fit in the destination.
• A widening conversion, as with storing Integer data in a Long, always
works, since the destination can always hold the source value.
CONTROL STRUCTURES
• Control structures consist of two things:
• Decision structures and
• Loops

I. Decision Structures
• Visual Basic procedures can test conditions and then, depending on the
results of that test, perform different operations.
• The decision structures that Visual Basic supports include:
• If...Then
• If...Then...Else
• Select Case
I. DECISION STRUCTURES…

If...Then
• Use an If...Then structure to execute one or more statements
conditionally.
• You can use either single-line syntax or multiple-line block syntax:
If condition Then statement
If condition Then
statements
End If

• The condition is usually a comparison specified using relational operators.


• Visual Basic interprets this value as True or False
• If condition is True, Visual Basic executes all the statements following the
Then keyword.
I. DECISION STRUCTURES…
• You can use either single-line or multiple-line syntax to execute just one
statement conditionally:
If mark >= 50 Then status = “Pass”
If mark >= 50 Then
status = “Pass”
End If
• The single-line form of If...Then does not use an End If
• If you want to execute multiple lines of code, you must use the multiple-
line block If...Then...End If syntax.
• The single line structure does not allow more than one line of code in
the then statement.
If mark >= 50 Then
status = ”pass”
Textbox1.text(“You have passed the course”)
End If
I. DECISION STRUCTURES…
If...Then...Else
• Use an If...Then...Else block to define several test conditions and an
associated block of statements which will execute when the test
condition is true:
If condition1 Then
[statementblock1]
[ElseIf condition2 Then
[statementblock2]] ...
[Else
[statementblockn]]
End If

• Notice that you can have any number of ElseIf clauses, or none at all.
• You can include an Else clause regardless of whether you have ElseIf clauses or
not.
I. DECISION STRUCTURES…
• For example, you want to give grade to students based on totalmark:
Dim totalmark as double
Dim grade as string
totalmark = text1.text
If totalmark > 80 Then
grade = ”A”
ElseIf totalmark > 60 Then
grade = ”B”
ElseIf totalmark > 40 Then
grade = ”C”
ElseIF totalmark > 30 Then
grade = ”D”
ElseIF totalmark <= 30 Then
grade = ”F”
End If
TextBox1.text(“Your grade is” & grade)
I. DECISION STRUCTURES…

• Notice that you can always add more ElseIf parts to your If...Then structure.

• However, this syntax can get tedious to write when each ElseIf compares the same
expression to a different value.

• For this situation, you can use a Select Case decision structure.

Select Case
• Visual Basic provides the Select Case structure as an alternative to If...Then...Else
for selectively executing one block of statements from among multiple blocks of
statements.

• A Select Case statement provides capability similar to the If...Then...Else statement,


but it makes code more readable when there are several choices.
I. DECISION STRUCTURES…

• A Select Case structure works with a single test expression that is


evaluated once, at the top of the structure.
• Visual Basic then compares the result of this expression with the values
for each Case in the structure.
• If there is a match, it executes the block of statements associated with
that Case:

Select Case testexpression


Case expressionlist1
[statementblock-1]
Case expressionlist2
[statementblock-2]
[Case Else
[statementblock-n]
End Select
I. DECISION STRUCTURES…

• Each expressionlist is a list of one or more values.


• You can specify expressionlist in three different ways:
Range: you can specify range of possible of values.
• We use keyword To to do this.
E.g Case 30 To 50

Comparison: you can specify greater or less relationships for the


value.
• We use keyword Is to do this.
E.g Case Is<30, Case Is>=80, Case Is>50

• List: you can list down the possible values.


I. DECISION STRUCTURES…
using range using comparison
Dim totalmark as double Dim totalmark as double
Dim grade as string Dim grade as string
totalmark = text1.text totalmark = text1.text
Select Case totalmark Select Case totalmark
Case 80 To 100 Case Is >= 80
grade = ”A” grade = ”A”
Case 60 To 79 Case Is >= 60
grade = ”B” grade = ”B”
Case 40 To 59 Case Is >= 40
grade = ”C” grade = ”C”
Case 30 To 39 Case Is >= 30
grade = ”D” grade = ”D”
Case Is < 30 Case Is < 30
grade = ”F” grade = ”F”
Case Else case Else
Text1.text(“Incorrect mark”) Text1.text(“Incorrect mark”)
End Select End Select
Text1.text(grade) Text1.text(grade)
II. LOOPS
• Loops allow you to execute one or more lines of code repetitively.
• It is used to carry out jobs that can be solved by repetition.
• For example, think of calculating factorials.
• It is not feasible to calculate large factorials like 1000! or 10000!
etc. using formula b/c it takes hours or even days.
• But using loop, it could be calculated easily by doing the same thing
over and over again.
• The loop structures that Visual Basic supports include:
– For...Next
– Do...Loop
– For Each...Next
II. LOOPS…
A. For...Next
• The For…Next loop is one of the oldest loop structures in
programming languages.
• Unlike the other loops, the For…Next loop requires that you know
how many times the loop will be executed.
• The For…Next loop uses a variable (it’s called the loop’s counter)
that increases or decreases in value during each repetition of the
loop.
• The syntax is:
For counter [As datat ype] = start To end [Step increment]
Statements
Next [counter]
II. LOOPS…
• The arguments counter, start, end, and increment are all numeric.
• counter: is a control variable that counts how many times the
loop has been executed.
• It is incremented by the loop itself, no need to increment it
directly.
• start: this is the initial value; It is the starting point for the loop.
• end: the control that stops the loop; When this value is reached,
the loop ends.
• increment: specifies by how much the loop is incremented or
decremented.
• If you do not include this part in the loop, it is incremented by 1
by default.
II. LOOPS…
• Example:This code displays even numbers from 0 to 100:
Private Sub Form_Click () Handles mybase.click
Dim i As Integer
For i = 0 To 100
If i mod 2 = 0 then
TextBox1.AppendText(cstr(i) + VbCrLf)
End if
Next
End Sub
II. LOOPS…
• Example: the following program calculates factorial (n!).
• n! = nxn-1xn-2xn-3x…x3x2x1

Private sun Button1_click(…) handles Button1.Click


Dim r as Integer = 1, n as integer
Dim i as Integer
n = text1.text ‘accept the number from textbox
For i = n to 1 step -1
r=r*I
Next
textresult.text = r ‘display the result on textbox
End sub
II. LOOPS…
• The single most important thing to keep in mind when working
with For…Next loops is that the loop’s counter is set at the
beginning of the loop.
• Changing the value of the end variable in the loop’s body won’t
have any effect.
• For example, the following loop will be executed 10 times, not
100 times:
Dim endValue as Integer, i as integer
endValue = 10
For i = 0 To endValue
endValue = 100
Console.Write(i)
Next i
II. LOOPS…

• To create a loop with a counter pattern other than 1, 2, 3, 4 and so on


• you can specify a different value for start in the loop, and then
• use the step keyword to increment/decrement the counter at
different intervals.
• Example:
Dim t as Integer
For t = 5 to 25 step 5
textbox1.AppendText(t + vbCrLf)
Next
NESTED FOR LOOP

• we can use for loop inside another for loop


• The inner loop is executed fully when outer loop is executed one time.
• The syntax for a nested For loop statement in VB.Net is as follows:
For counter1 [ As datatype1 ] = start1 To end1 [ Step step1 ]
For counter2 [ As datatype2 ] = start2 To end2 [ Step step2 ]
...
Next [ counter2 ]
Next [ counter 1]

For i As Integer = 1 To 3
For j As Integer = 1 To 3
11 12 13
TextBox3.AppendText(i.ToString() + j.ToString() + " ")
Next 21 22 23
TextBox3.AppendText(vbCrLf) 31 32 33
Next
NESTED FOR LOOP

Example:Write a vb program to print the following pattern

For i As Integer = 1 To 5
For j As Integer = 1 To i
TextBox3.AppendText(j.ToString() + " ")
Next
TextBox3.AppendText(vbCrLf)
Next
II. LOOPS…
B. Do...Loop
• Do loops work well when you don't know how many times you
need to execute the statements in the loop.
• When you know you must execute the statements a specific
number of times, however, a For…Next loop is a better choice.
• Use a Do loop to execute a block of statements an indefinite
number of times.
• There are several variations of the Do...Loop statement, but each
evaluates a numeric condition to determine whether to continue
execution.
• As with If...Then, the condition must be a value or expression that
evaluates to False (zero) or to True (nonzero).
II. LOOPS…
1.Do while Loop
• In Do while...Loops, the statements execute as long as the condition
is True:
Do While condition
statements
Loop
• When Visual Basic executes this Do loop, it first tests condition.
• If condition is False (zero), it skips past all the statements.
• If it's True (nonzero), Visual Basic executes the statements and
then goes back to the Do While statement and tests the condition
again.
II. LOOPS…

• Consequently, the loop can execute any number of


times, as long as condition is nonzero or True.
• The statements never execute if condition is initially
False.
• Example: a program that prints odd numbers
between 0 and 100
Dim counter as double
counter = 1
Do While counter <= 100
If counter mod 2 = 1 then
II. LOOPS…
2. Do until
• The Do Until…Loop continues execution as long as the condition
is False unlike Do While…Loops which work when the condition
is true.

Do until condition
Statements
Loop
• Here, we specify the condition in which the loop stops, not when
it works which is the case in Do While…Loops.
II. LOOPS…
• Example: a program that prints odd numbers between 0 and 100
Dim counter as double
counter = 1
Do until counter > 100
If counter mod 2 = 1 then
Console.WriteLine(counter)
End If
counter = counter + 1 ‘increment control variable
Loop
II. LOOPS…

3. Do…Loop while

• Another variation of the Do…Loop statement executes the


statements first and then tests condition after each execution.

• This variation guarantees at least one execution of statements:

Do

statements

Loop While condition


II. LOOPS…
• Example: a program that checks if a number is a multiple of 3 or
not
Dim n as double = 1
Do
If n mod 3 = 0 then
Console.WriteLine(n)
End If
n = n + 1 ‘increment control variable
Loop While n <= 100
II. LOOPS…

4. Do…Loop until

• It is also possible to declare similar loop using Do …Loop Until


which executes the loop at least once.

Do

Statements

Loop Until condition


II. LOOPS…
• Example: a program that checks if a number is a multiple of 3 or not
Dim n as double = 1
Do
If n mod 3 = 0 then
Console.WriteLine(n)
End If
n = n + 1 ‘increment control variable
Loop until n > 100
II. LOOPS…
• The following table summarizes the four types of DO…Loops
Loop zero or more times Loop at least once

Do Until condition Do
statements statements
Loop Loop Until condition
Do While condition Do
statements statements
Loop Loop While condition

• You need a control variable that controls the operation of all


II. LOOPS…
5.While…End Loop:
• Use a While...End While structure when you want to repeat a set
of statements an indefinite number of times.
• The syntax is:
While condition
statements
End While

• The While statement always checks the condition before it starts


the loop.
• Looping continues while the condition remains True.
• If condition is False when you first enter the loop, it doesn’t run
even once.
II. LOOPS…

• Example: a while loop that displays numbers from 0 to 10

Dim index As Integer = 0

While index <= 10

textbox1.appendtext((cstr(index))

index += 1

End While

• Output:

0 1 2 3 4 5 6 7 8 9 10
II. LOOPS…
5. For Each...Next
• A For Each...Next loop is similar to a For...Next loop.
• It repeats for each element in a collection of objects or in an array instead of
repeating the statements a specified number of times.
• This is especially helpful if you don't know how many elements are in a
collection or an array.
• Here is the syntax for the For Each...Next loop:
For Each element In group
statements
Next element
group: the name of object or array or collection to navigate through.
element: variable that takes control of each element of object or array or
collection during navigation.
II. LOOPS…

• Example: A program that navigates through an array

Dim a() As Integer = {1, 2, 3, 4, 5}

Dim b As Integer

For Each b In a

Console.WriteLine(b)

Next
II. LOOPS…
Exiting a Control Structure
• The Exit statement allows you to exit directly from a loop, Sub procedure, or
Function procedure.
• Exit For can appear anywhere inside a For loop, and Exit Do can appear as
many times as needed inside a Do loop:

For counter = start To end [Step increment]


[statementblock]
Exit For
[statementblock]
Next [counter]

Do {While | Until} condition


[statementblock]
Exit Do
[statementblock]
Loop
II. LOOPS…
• The Exit Do statement works with all versions of the Do loop
syntax.
• Exit For and Exit Do are useful because sometimes it's appropriate
to quit a loop immediately, without performing any further
iterations.
• For example, when searching a detail of a given student in a list..

Private Sub Form_Click()


Dim ID(100) as string, name(100)as string, GPA(100) as string
For i = 0 to 100
If ID(i) = “123/97” Then
Console.WriteLine(Id(i) & name(i) & GPA(i))
II. LOOPS…
Example:
For i As Integer = 1 To 10
If i = 5 Then Output:
Exit For
End If 11
TextBox1.AppendText(i.ToString)
Next
12
For i As Integer = 1 To 3 13
For j As Integer = 1 To 3
If i = 2 And j = 2 Then 21
Exit For
End If 31
TextBox3.AppendText(i.ToString() + j.ToString() + vbCrLf)
Next 32
Next
33
II. LOOPS…
Continue Statement
• Continue statement transfers control immediately to the next
iteration of a loop.
• You can transfer from inside a Do, For, or While loop to the
next iteration of that loop.
• Control passes immediately to the loop condition test. The
syntax is:
Continue { Do | For | While }

• Example: a program that displays odd numbers


Dim t as Integer
For t = 0 to 10
II. LOOPS…
example
For i As Integer = 1 To 10
If i = 5 Then
Continue For
End If Output:
TextBox1.AppendText(i.ToString)
Next
11
12
For i As Integer = 1 To 3
For j As Integer = 1 To 3 13
If i = 2 And j = 2 Then 21
Continue For
End If 23
TextBox3.AppendText(i.ToString() + j.ToString() + vbCrLf) 31
Next
Next 32
33
EXERCISE

• Write a program in vb to display the first 10 natural numbers.

• Write a vb program to display even numbers from 1 to 100.

• Write a vb program to compute sum of first n natural numbers.


Subroutine And Functions

• You can simplify programming tasks by breaking programs into


smaller logical components.

• These components — called procedures — can then become


building blocks that let you enhance and extend Visual Basic.

• Procedures are useful for condensing repeated or shared tasks,


such as frequently used calculations, text and control manipulation,
and database operations.
Cont…

• There are two major benefits of programming with


procedures:

• Procedures allow you to break your programs into


discrete logical units, each of which you can debug more
easily than an entire program without procedures.

• Procedures used in one program can act as building blocks


for other programs, usually with little or no modification.
Cont…
• There are two types of procedures used in Visual Basic:
Function procedures:
• Function procedures are called by name from event procedures or other
procedures.
• Often used for calculations, function procedures can receive arguments and
always return a value in function name
Sub procedures:
• Sub procedures are called by name from event procedures or other
procedures.
• They can receive arguments and also pass back modified values in an
argument list.
• Unlike functions, however, Sub procedures don’t return values associated
with their particular Sub procedure names.
1. Sub Procedures

• A sub procedure, also called subroutine, is a block of statements


that carries out a well-defined task.
• Sub procedures is placed within a set of Sub…End Sub statements
and can be invoked by name.

• The syntax for a Sub procedure is:


[Private|Public] Sub procedurename([arguments])
statements
End Sub
1. Sub Procedures…

• Each time the procedure is called, the statements between


Sub and End Sub are executed.

• Sub procedures can be placed in standard modules, class


modules, and form modules.

• Sub procedures are by default Public in all modules, which


means they can be called from anywhere in the application.

• The arguments for a procedure are like a variable declaration,


declaring values that are passed in from the calling procedure.
1. Sub Procedures…

• There are two types of Sub procedures:


• general procedures and
• event procedures
A. General Procedures
• A general procedure tells the application how to perform a
specific task.
• Once a general procedure is defined, it must be specifically
invoked by the application.
Cont…
• By contrast, an event procedure remains idle until called upon to
respond to events caused by the user or triggered by the system.
• Several different event procedures might need the same actions
performed.
• The syntax for general procedure is:
Cont…

• procedurename: is a unique name given to a procedure for


identification purpose.
• argument: are data that the procedure accepts and use for its
processing activity.
• For example a program that gives grade to students can
accept total mark as argument.
• Arguments are separated by comma when we have more
than one.
Cont…

• Example: a procedure that calculates simple


interest for a given principal
Private sub calculatesimpleinterest()
Dim principal as Double
Dim rate as double
Dim year as integer
Dim interest as Double
principal = txtprincipal.text
rate = txtinterest.text
Cont…

Private sub calculatesimpleinterest(principal as Double, rate as double,


year as integer)
Dim interest as Double
interest = principal * rate * year
lblinterest.text= interest
End sub
Private sub Button1_click(Byval sender as System.Object, Byval e as
System.EventArgs) Handles Button1.click
Dim pr as Double, yr as integer, rt as double
pr = txtprincipal.text
rt = txtinterest.text
1. Sub Procedures…
B. Event Procedures
• An event handler is a segment of code that is executed each time
the event occurs.
• When the user clicks a control, the control’s Click event handler
executes.
• This handler is a subroutine that performs all the actions you want
to perform when the control is clicked.
• Every application is made up of event handlers, which contain code to
react to user actions.
• Event handlers need not return any results, and they’re
implemented as subroutines.
1. Sub Procedures…

• An event procedure for a control combines the control's actual


name an underscore (_), and the event name.

• For instance, if you want a command button named cmdPlay to


invoke an event procedure when it is clicked, use the procedure

sub cmdPlay_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles cmdPlay.Click.

• An event procedure for a form combines the word "Form," an


underscore, and the event name.
1. Sub Procedures…
• If you want a form to invoke an event procedure when it is clicked,
use the procedure Form_Click.
• Like controls, forms do have unique names, but they are not used
in the names of event procedures.
Syntax for a control event
Private Sub controlname_eventname (ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Controlname.event
statements
End Sub
Syntax for a form event

Private Sub Form_eventname (ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles MyBase.event
statements
End Sub
1. Sub Procedures…
• Controlname.event and MyBase.event: indicates what event triggers
the execution of the code.
• Example: a program that calculates simple interest
Private sub cmdinterest_click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles cmdinterest.Click
Dim principal as Double
Dim rate as doubleDim year as integer
Dim interest as Double
principal = txtprincipal.text
rate = txtinterest.text
year = txtyear.text
interest = principal * rate * year
lblinterest.text = interest
End sub
1. Sub Procedures…
Event-Handler Arguments
• Event handlers never return a result, so they’re implemented as
subroutines.
• There are two arguments common to all event handlers, which
pass information about the object and the action that invoked the
event.
• You may have noticed that the subroutines that handle events
accept two arguments: sender and e.
• Here’s the declaration of the Click event handler for a button:
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs) Handles Button1.Click
End Sub
1. Sub Procedures…
• The sender argument conveys information about the
object that initiated the event
• we use this argument in our code to find out the type of
the object that raised the event.
• The following two statements in a button’s Click event
handler will print the values shown in bold on the
Output window:

Console.WriteLine(sender.ToString)
' System.Windows.Forms.Button,Text: Button1
Console.WriteLine(sender.GetType)
‘ System.Windows.Forms.Button
1. Sub Procedures…

• The second argument contains all the information you need


to process the event.

• The e argument is an object that exposes some properties,


which vary depending on the type of the event and the
control that raised the event.

• A TextBox control, for example, raises several events when a


key is pressed, in addition to the events of the mouse.
2. Function Procedure
• A function is similar to sub procedures, but a function returns
a result.
• Sub procedures perform a task and don’t return anything to
the calling program; functions commonly carry out
calculations and return the result.
• Because they return values, functions, like variables, have data
types.
• The value you pass back to the calling program from a
function is called the return value, and its type must match
the data type of the function.
• Functions can accept arguments, just like subroutines.
2. Function Procedures…

• The syntax for a Function procedure is:


[Private|Public] Function functionname ([arguments]) As type
Statements
[Return value]
End Function

The parts:
• FunctionName is the name of the function you are creating.
• As Type is a pair of keywords that specifies the function return type.
• Argument is a list of optional arguments to be used in the function.
• Each argument should also be declared as specific type.
• By default,Visual Basic adds the ByVal keyword to each argument.
2. Function Procedures…

differences between Sub and Function procedures:


• Function procedures have data types, just as variables do.
• This determines the type of the return value.
• In the absence of an As clause, the type is the default Object
type.
• Function returns value.
• After processing data, functions can return back the result to
calling procedure.
2. Function Procedures…

• Function can return values in two ways:

• using return keyword or

• assign to functionname

• You can return a value by assigning it to the functionname


itself.

• The syntax is:


return value
Functionname = value
2. Function Procedures…

• Example: two types of returning value


Function adder(ByVal x as Integer, ByVal y as Integer) as Integer
Dim sum as Integer
sum = x + y
return sum
End Function
Function adder(ByVal x as Integer, ByVal y as Integer) as Integer
Dim sum as Integer
sum = x + y
adder = sum
End Function
2. Function Procedures…

• Example a function that calculates the hypotenuse of a right


triangle:
Function Hypotenuse (A As Integer, B As Integer) As Double
Dim hyp as Double
hyp = Math.Sqrt(A ^ 2 + B ^ 2)
Hypotenuse = hyp ‘returns the hypotenuse to the caller
End Function
Private sub command1_click() Handles Command1.Click
Dim width as double, height as double, hyp as double
width = text1.text
Passing Arguments To Procedures

• Usually the code in a procedure needs some information to be


given to it to do its job.

• This information consists of variables passed to the procedure


when it is called.

• When a variable is passed to a procedure, it is called an argument.


Passing Arguments To Procedures

• Argument could be passed to procedures in two ways.


• These are:
– Pass by value
– Pass by reference

A. Passing Arguments By Value


• Only a copy of a variable is passed when an argument is
passed by value.
• If the procedure changes the value, the change affects only
the copy and not the variable itself.
• Use the ByVal keyword to indicate an argument passed by
value.
Private function findlargest(Byval a as integer, Byval b as integer, Byval c as
Integer) As Integer
Dim largest as Integer
If a > b and a > c then
largest = a
Elseif b > a and b > c then
largest = c
Elseif c > a and c > b then
largest = c
Endif
‘ swap the content of a, b, and c
c=a
a=b
Passing Arguments To Procedures

B. Passing Arguments by Reference

• Passing arguments by reference gives the procedure access to


the actual variable contents in its memory location.

• As a result, the variable's value can be permanently changed by


the procedure to which it is passed.

• Use the ByRef keyword to indicate an argument passed by


reference.
• Example: a program that finds the largest number from three numbers
Private function findlargest(ByRef a as integer, ByRef b as integer, ByRef c
as Integer) As Integer
If a > b and a > c then
Largest = a
Elseif b > a and b > c then
Largest = c
Elseif c > a and c > b then
Largest = c
End If
‘swap the content of a, b, and c
c = a :a = b :b = c
findlargest = largest
End function
Private sub Button1_click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.click
Important Functions (Methods)

Function for Working with Strings


• The String class implements the String data type, which is one of
the richest data types in terms of the members it exposes.
• To create a new instance of the String class, you simply declare a
variable of the String type.
• You can also initialize it by assigning to the corresponding variable
a text value:
Dim title As String = “Mastering VB.NET”

• The String class has methods and properties by which we can


manipulate the string.

I. Properties
Important Functions…

Length
• The Length property returns the number of characters in the
string, and it’s read-only.
Dim title As String = “Mastering VB.NET”
Dim len as Integer
len = title.Length

Chars
• The Chars property is an array of characters that holds all the
characters in the string.
• Use this property to read individual characters from a string
based on their location in the string.
Important Functions…

Methods
• All the functionality of the String class is available through
methods.
• Most of these methods are shared methods: you must supply the
string on which they act as argument.
• They don’t modify the current instance of the String class; instead,
they return a new String value.

Compare()
• This method compares two strings and returns
• a negative value if the first string is less than the second,
• a positive value if the second string is less than the first,
Important Functions…

• The method accepts a third argument, which is a True/False value


indicating case-sensitive (if True) or not:
String.Compare(str1, str2, case)
• Another form of the Compare method allows you to compare
segments of two strings
String.Compare(str1, index1, str2, index2, length)
index1 and index2 are the starting locations of the segment to be
compared in each string.
• The two segments must have the same length, which is specified
by the last argument.

• Example:
Important Functions…

Concat()
• This method concatenates two or more strings and forms a new one
• The simpler form of the Concat method has the following syntax, and it’s
equivalent to the & operator:
newString = String.Concat(string1, string2)
• This statement is equivalent to the following:
newString = string1 & string2

• To use this form of the method, store all the strings you want to
concatenate into a string array and then call the Concat method, as
shown in this code segment:
Dim strings() As String = {“string1”,“string2”,“string3”}
Dim longString As String
longString = String.Concat(strings)
Important Functions…
EndsWith(), StartsWith()
• These two methods return True if the string ends or starts with a user-supplied
substring.
• The syntax of these methods is
found = str.EndsWith(string)
found = str.StartsWith(string)

• The two statements following the declaration of the name variable are
equivalent:
Dim name As String = “Visual Basic.NET”
If name.StartsWith(“Visual”) Then ...

• The comparison performed by the StartsWith method is case-sensitive.


• If you don’t care about the case, you can convert both the string and the
substring to uppercase, as in the following example:
If name.ToUpper.StartsWith(“VIS”) Then ...
Important Functions…
IndexOf(), LastIndexOf()
• The IndexOf method starts searching from the beginning, and the LastIndexOf
method starts searching from the end of the string.
• Both return an integer, which is the order of the substring’s first character in
the larger string
• When there’s a match, they return the index of the first character of the match.
• If there’s no match, they returns -1; so you’ll know your search turned up empty.

• To locate a single character in a string, use the following forms of the IndexOf
method:
String.IndexOf(ch)
String.IndexOf(ch, startIndex)
String.IndexOf(ch, startIndex, count)

• The startIndex argument is the location in the string, where the search will start,
and the count argument is the number of characters that will be examined.
Important Functions…
• Example: searches the word Visual is a text box
Dim pos As Integer, bloc as Integer
Dim str as String = "shoestrings new strings"
pos = str.IndexOf("string") 'returns 4
bloc = str.LastIndexOf("string") ' returns 16

Replace()
• This method replaces all instances of a specified character (or substring) in a
string with a new one.
• It creates a new instance of the string, replaces the characters as specified by its
arguments, and returns this string:
newString = str.Replace(oldChar, newChar)
• Example:
Dim txt as String, newTxt As String
txt = “Welcome to VB7”
newTxt = txt.Replace(“VB7”, “VB.NET”) ‘returns Welcome to VB.NET
Important Functions…

Remove()
• The Remove method removes a given number of characters from a
string, starting at a specific location
newString = str.Remove(startIndex, count)
where startIndex is the index of the first character to be removed and
count is the number of characters to be removed.

• Example:
strSpelling = "misssspelled"
strCorrected = strSpelling.Remove(2, 2)
• In this example, it starts with the first “s” because it has an index of 2
and it removes 2 character.
• The result is “misspelled”, which is the correct spelling.
Important Functions…

Insert()
• The Insert method adds characters to a string.
• There are two arguments, the starting index and the character(s)
to be added to the string.

• For example:
strPresident = "Harry Truman"
strInserted = strPresident.Insert(6, "S. ")
lblInserted.Text = strInserted
• It starts where the “T” is because that character has an index of 6
and inserts “S. ”.
• The result is “Harry S.Truman”.
Important Functions…

Split()
• You can split a long string into smaller ones with the Split
method, whose syntax is
strings() = str.Split(delimiters)
• where delimiters is an array of characters and string is the
string to be split.
• The string is split into sections that are separated by any
one of the delimiters specified with the first argument.
• These strings are returned as an array of strings.
Important Functions…

Example: splitting sentences to words

Dim str As String =“Carl Friedrich Gauss is German mathematician”

Dim words() As String

words = str.Split(" ")

For i = 0 To words.Length - 1

Console.WriteLine(words(i))

Next
Important Functions…
Trim(),TrimStart(),TrimEnd()
• The Trim method removes spaces from the beginning and end of a string.
• TrimStart removes leading spaces and TrimEnd removes trailing spaces.
• The default character is a space, but other characters, when specified, can be
trimmed as well:
strExtra = " SPACE "
strTrimmed = strExtra.Trim()
lblOutput.Text = strTrimmed
strExtra = " SPACE "
strTrimmed = strExtra.TrimStart()
lblTrimmed.Text = strTrimmed
strExtra = " SPACE "
strTrimmed = strExtra.TrimEnd()
lblTrimmed.Text = strTrimmed
• Trim is particularly useful when working with user input.
• A user may accidentally add extra spaces at the beginning or end of their input.
Important Functions…

Left(string, numberofcharacters)
• Returns the first N characters of a String where N is an Integer
parameter indicating the number of characters to return.
• Often you are only concerned with the first few characters of a
String. Left is a great way to look at only the beginning of a String.
Syntax: String = Microsoft.VisualBasic.Left(String, Integer)
Important Functions…

Right(string, numberofcharacters)
• Returns the last N characters of a String where N is an Integer
parameter indicating the number of characters to return
• Often you are only concerned with the last few characters of a String.
Right is a great way to look at only the end of a String
Syntax: String = Microsoft.VisualBasic.Right(String, Integer)
Important Functions…

Mid(string, startposition [, numberofcharacters])


• Returns a specific number of characters of a String allowing the
developer to indicate where to start and how many characters
to return
• Often you wish to extract a portion of a String to use separately
from the rest of the String. This is often the case when working
with fixed-width data files
Syntax: String = Mid(String, Starting Position, Optional Length)
Important Functions…

Len(string)

• this returns the length of string (number of characters in the


string)

• Example:

Dim str as string

str =”two people”

Console.write( len(str)) ‘prints 10


Important Functions…

Ucase(stgring)
• Returns the String that is passed in all uppercase letters
• UCase can be used when the desired output is required to be in all
uppercase letters. It is also commonly used when you wish to
validate data entered by a user against a given string.

• Syntax: String = UCase(String)


Important Functions…

Lcase(string)

• Returns the String that is passed in all lowercase letters.


Example:

Dim note as string, rt as string

note = ”This is STRING Manipulation”

rt = Lcase(note) ‘this returns this is string manipulation


Important Functions…

Functions for Working with Numbers

• The following are functions that we use to manipulate numbers:

Val(string)

• This returns the numeric value of given string.

• It converts string to number.

• Example

Val(“23abc”) ‘returns 23

You might also like