101
Visual Basic 2005 Visual Basic 2005 II. PROGRAMMING FUNDAMENTALS MELJUN CORTES MELJUN CORTES

MELJUN CORTES Visual basic 2005 02 programming fundamentals

Embed Size (px)

Citation preview

Page 1: MELJUN CORTES Visual basic 2005   02 programming fundamentals

Visual Basic 2005Visual Basic 2005II. PROGRAMMING FUNDAMENTALS

MELJUN CORTESMELJUN CORTES

Page 2: MELJUN CORTES Visual basic 2005   02 programming fundamentals

Variables, Data Types and OperatorsVariables, Data Types and OperatorsObjectives

In this chapter you will learn:•To declare and use data of various types.•To declare and use user-defined types.•To use data type conversion functions.•The structure of a variable.•The different variable scopes.•To use constants and enumerated types.•To use various data manipulation operators.

2PROGRAMMING FUNDAMENTALS

Visual Basic 2005

Page 3: MELJUN CORTES Visual basic 2005   02 programming fundamentals

OverviewOverview

Data manipulation is the heart of any software application

You could choose to process the data the way that your computer's CPU does: bit by bit

But that quickly becomes tedious, so languages like Visual Basic include a variety of data types

Variables, Data Types and Operators

3PROGRAMMING FUNDAMENTALS

Visual Basic 2005

Page 4: MELJUN CORTES Visual basic 2005   02 programming fundamentals

Data TypesData Types

The .NET Common Language Runtime (CLR) includes the Common Type System (CTS)

CTS defines the data types that are supported by the CLR

Each .NET-enabled language implements a subset of the CLR data types

Variables, Data Types and Operators

4PROGRAMMING FUNDAMENTALS

Visual Basic 2005

Page 5: MELJUN CORTES Visual basic 2005   02 programming fundamentals

Data TypesData Types

In .NET, data types are special classes and structures whose instances manipulate a data value that must fall within the limited range of the data type

.NET provides data types for those subsets of data that programmers have found essential in software development

These data types make it possible to manipulate virtually any variation of data

Variables, Data Types and Operators

5PROGRAMMING FUNDAMENTALS

Visual Basic 2005

Page 6: MELJUN CORTES Visual basic 2005   02 programming fundamentals

Data TypesData Types

The .NET Framework implements nearly 20 of these essential core data types

The native VB data types are wrappers for the core data types

For instance, the VB Integer data type is a wrapper for the System.Int32 structure

Dim usesInt32 As Integer MessageBox.Show(usesInt32.MaxValue) ' Displays 2147483647Dim usesInt32 As Integer MessageBox.Show(usesInt32.MaxValue) ' Displays 2147483647

Variables, Data Types and Operators

6PROGRAMMING FUNDAMENTALS

Visual Basic 2005

Page 7: MELJUN CORTES Visual basic 2005   02 programming fundamentals

Value and Reference TypesValue and Reference Types

Data types in Visual Basic fall into two broad categories:◦ Value types◦ Reference types

Value types and reference types differ primarily in how they are stored in memory

Dim simpleValue As Integer = 5 Dim simpleValue As Integer = 5

Dim somewhereElse As New MyCustomClass Dim somewhereElse As New MyCustomClass

Variables, Data Types and Operators

7PROGRAMMING FUNDAMENTALS

Visual Basic 2005

Page 8: MELJUN CORTES Visual basic 2005   02 programming fundamentals

Value and Reference TypesValue and Reference Types

5

Variables, Data Types and Operators

8PROGRAMMING FUNDAMENTALS

SimpleValue

A variable (SimpleValue) of a valuetype (Integer) contains a value (5)of that type

(The arrow represents the memory address of

the MyCustomClass object)

Dim simpleValue As Integer = 5 Dim simpleValue As Integer = 5

Dim somewhereElse As New MyCustomClass Dim somewhereElse As New MyCustomClass

somewhereElse MyCustomClass

customValue

A variable (somewhereElse) of a referencetype (MyCustomClass) contains a reference(memory address) to an object of that type

Visual Basic 2005

Page 9: MELJUN CORTES Visual basic 2005   02 programming fundamentals

VB Data TypesVB Data Types

Visual Basic implements all of the core .NET data types as of the 2005 edition of the language

These basic data types provide a broad range of features for managing all categories of data

The data types can be arranged into five groups by the type of data managed

Variables, Data Types and Operators

9PROGRAMMING FUNDAMENTALS

Visual Basic 2005

Page 10: MELJUN CORTES Visual basic 2005   02 programming fundamentals

VB Data TypesVB Data Types

Data Type Group Description

Boolean Data This single data type provides a single bit of data, either True or False.

Character Data Visual Basic includes data types that manage either single characters or long strings of characters.

Date and Time Data A single data type manages both date and time values.

Floating Point Data The various floating point data types each manage a subset of rational numbers. Some of these data types provide more mathematical accuracy than others.

Integer Data The integer data types, and there are many, store integer values between a data type-defined minimum and maximum value. Some of these data types support negative numbers.

PROGRAMMING FUNDAMENTALS 10

Variables, Data Types and Operators

Visual Basic 2005

Page 11: MELJUN CORTES Visual basic 2005   02 programming fundamentals

VB Data TypesVB Data Types

Type Size in Bytes Value Range

SByte 1 128 to 127

Byte 1 0 to 255

Boolean 2 True or False

Char 2 0 to 65,535 (representing the Unicode character set)

Short 2 32,768 to 32,767

UShort 2 0 to 65,535

Integer 4 2,147,483,648 to 2,147,483,647

UInteger 4 0 to 4,294,967,295

Continued…

PROGRAMMING FUNDAMENTALS 11

Variables, Data Types and Operators

Visual Basic 2005

Page 12: MELJUN CORTES Visual basic 2005   02 programming fundamentals

VB Data TypesVB Data TypesPROGRAMMING FUNDAMENTALS 12

Variables, Data Types and Operators

Type Size in Bytes Value Range

Single 4 negative range: 3.4028235E+38 to 1.401298E-45positive range: 1.401298E45 to 3.4028235E+38

Long 8 9,223,372,036,854,775,808 to 9,223,372,036,854,775,807, inclusive

ULong 8 0 to 18,446,744,073,709,551,615, inclusive

Double 8 negative range: 1.79769313486231570E+308 to 4.94065645841246544E324positive range: 4.94065645841246544E324 to 1.79769313486231570E+308

Date 8 0:00:00 on 1 January 0001 to 23:59:59 on 31 December 9999

Decimal 16 Range with no decimal point: ±79,228,162,514,264,337,593,543,950,335Range with 28 places to the right of the decimal point: ±7.9228162514264337593543950335The smallest nonzero number is: ±0.0000000000000000000000000001 (±1E28)

String Depends on platform

up to approximately 2 billion Unicode characters

Visual Basic 2005

Page 13: MELJUN CORTES Visual basic 2005   02 programming fundamentals

User-defined Data TypesUser-defined Data Types

These user-defined data types extend the basic data types with new types of your own choosing

Structures can be used to define user-defined types

Variables, Data Types and Operators

13PROGRAMMING FUNDAMENTALS

[Public|Private|Friend] Structure structureName member declarations End Structure

[Public|Private|Friend] Structure structureName member declarations End Structure

Visual Basic 2005

Page 14: MELJUN CORTES Visual basic 2005   02 programming fundamentals

User-defined Data TypesUser-defined Data Types

The simplest and most common use of structures is to encapsulate related variables, or fields

Variables, Data Types and Operators

14PROGRAMMING FUNDAMENTALS

Structure Person Public Name As String Public Address As String Public City As String Public State As String Public Zip As String Public Age As Short End Structure

Structure Person Public Name As String Public Address As String Public City As String Public State As String Public Zip As String Public Age As Short End Structure

Visual Basic 2005

Page 15: MELJUN CORTES Visual basic 2005   02 programming fundamentals

User-defined Data TypesUser-defined Data Types

A standard declaration defines a variable of type Person:

Members of the structure are accessed using the standard "dot" syntax that applies also to classes:

Variables, Data Types and Operators

15PROGRAMMING FUNDAMENTALS

Dim onePerson As Person Dim onePerson As Person

onePerson.name = “Beethoven” onePerson.name = “Beethoven”

Visual Basic 2005

Page 16: MELJUN CORTES Visual basic 2005   02 programming fundamentals

Data Type ConversionData Type Conversion

The process of converting a value of one data type to another is called conversion or casting

A conversion can be applied to a literal value, variable, or expression of a given type

Visual Basic includes several conversion functions that cast data between the basic data types

Variables, Data Types and Operators

16PROGRAMMING FUNDAMENTALS

Visual Basic 2005

Page 17: MELJUN CORTES Visual basic 2005   02 programming fundamentals

Data Type ConversionData Type Conversion

Casts and conversions can be widening or narrowing

Variables, Data Types and Operators

17PROGRAMMING FUNDAMENTALS

Dim miniSize As Byte = 6 Dim superSize As Long superSize = CLng(miniSize) ' Convert Byte variable to Long superSize = CLng("12") ' Convert String literal to Long

Dim miniSize As Byte = 6 Dim superSize As Long superSize = CLng(miniSize) ' Convert Byte variable to Long superSize = CLng("12") ' Convert String literal to Long

Dim smallerData As Integer = 3948 Dim largerData As Long

largerData = smallerData

Dim smallerData As Integer = 3948 Dim largerData As Long

largerData = smallerData

Visual Basic 2005

Page 18: MELJUN CORTES Visual basic 2005   02 programming fundamentals

Data Type ConversionData Type Conversion

Visual Basic includes conversion functions for the basic data types:

PROGRAMMING FUNDAMENTALS 18

Variables, Data Types and Operators

Function Description

CBool() Converts any valid string or numeric expression to Boolean. When a numeric value is converted to Boolean, any nonzero value is converted to true, and zero is converted to False.

CByte() Converts any numeric expression in the range of a Byte to Byte, rounding any fractional part.

CChar() Converts the first character of a string to the Char data type.

CDate() Converts any valid representation of a date or time to Date.

CDbl() Converts any numeric expression in the range of a Double to Double.

CDec() Converts any numeric expression in the range of a Decimal to Decimal.

CInt() Converts any numeric expression in the range of an Integer to Integer, rounding any fractional part.

Visual Basic 2005

Page 19: MELJUN CORTES Visual basic 2005   02 programming fundamentals

Data Type ConversionData Type ConversionPROGRAMMING FUNDAMENTALS 19

Variables, Data Types and Operators

Function Description

CLng() Converts any numeric expression in the range of a Long to Long, rounding any fractional part.

CObj() Converts any expression to an Object. This is useful when you need to treat a value type as a reference type.

CSByte() New in 2005. Converts any numeric expression in the range of an SByte to SByte, rounding any fractional part.

CShort() Converts any numeric expression in the range of a Short to Short, rounding any fractional part.

CSng() Converts any numeric expression in the range of a Single to Single.

CStr() Converts an expression to its string representation. Boolean values are converted to either "True" or "False." Dates are converted based on the date format defined by the regional settings of the host computer.

CType() Provides generalized casting, allowing an object or expression of any type to be converted to another type. It works with all classes, structures, and interfaces.

Visual Basic 2005

Page 20: MELJUN CORTES Visual basic 2005   02 programming fundamentals

VariablesVariables

A variable can be defined as an entity that has the following six properties:◦ Name◦ Address◦ Data type◦ Value◦ Scope◦ Lifetime

Variables, Data Types and Operators

20PROGRAMMING FUNDAMENTALS

Visual Basic 2005

Page 21: MELJUN CORTES Visual basic 2005   02 programming fundamentals

VariablesVariables

A variable declaration is an association of a variable name with a data type

PROGRAMMING FUNDAMENTALS 21

Dim createMeNow As IntegerDim createMeNow As Integer

Dim createMeNow As Integer = New IntegerDim createMeNow As Integer = New Integer

Dim createMeNow As New IntegerDim createMeNow As New Integer

Variables, Data Types and Operators

Visual Basic 2005

Page 22: MELJUN CORTES Visual basic 2005   02 programming fundamentals

Variable ScopeVariable Scope

All variables declared within a function, sub procedure, or property are local variables

These variables may be used only within that routine

Local variables generally have procedure-level scope

PROGRAMMING FUNDAMENTALS 22

Variables, Data Types and Operators

Visual Basic 2005

Page 23: MELJUN CORTES Visual basic 2005   02 programming fundamentals

Variable ScopeVariable Scope

These local variables often appear immediately upon entering the code of the procedure

PROGRAMMING FUNDAMENTALS 23

Public Sub DoTheWork( ) Dim localInt As Integer Dim localEmp As New Employee

. . .End Sub

Public Sub DoTheWork( ) Dim localInt As Integer Dim localEmp As New Employee

. . .End Sub

Local variables

Variables, Data Types and Operators

Visual Basic 2005

Page 24: MELJUN CORTES Visual basic 2005   02 programming fundamentals

Variable ScopeVariable Scope

Code blocks are sets of statements contained within an If statement, a For loop, a With statement, or any other similar block of code that has separate starting and ending statements

PROGRAMMING FUNDAMENTALS 24

Public Sub DoTheWork(ByVal fromWhen As Date, ByVal howMuch As Decimal) If (fromWhen < Today) Then ' ----- This variable is available within the outer-most ' If block, which also includes the inner-most block. ' It is not available outside the outer-most If block. Dim simpleCalculation As Integer If (howMuch > 0) Then ' ----- This variable is only available within the ' inner-most If block. Dim complexCalculation As Integer End If End If End Sub

Public Sub DoTheWork(ByVal fromWhen As Date, ByVal howMuch As Decimal) If (fromWhen < Today) Then ' ----- This variable is available within the outer-most ' If block, which also includes the inner-most block. ' It is not available outside the outer-most If block. Dim simpleCalculation As Integer If (howMuch > 0) Then ' ----- This variable is only available within the ' inner-most If block. Dim complexCalculation As Integer End If End If End Sub

Variables, Data Types and Operators

Visual Basic 2005

Page 25: MELJUN CORTES Visual basic 2005   02 programming fundamentals

Variable ScopeVariable Scope

Local variables can extend their lifetime beyond the execution timeline of the procedure in which they reside by declaring them Static

PROGRAMMING FUNDAMENTALS 25

Variables, Data Types and Operators

Static longLasting As Integer = 0Static longLasting As Integer = 0

Static keyword

Visual Basic 2005

Page 26: MELJUN CORTES Visual basic 2005   02 programming fundamentals

Variable ScopeVariable Scope

All variables declared within a class (or structure or module), but outside of any procedure within that class, have type-level scope

However, the scope of these variables can go beyond the type level through the use of an access modifier

PROGRAMMING FUNDAMENTALS 26

Variables, Data Types and Operators

Visual Basic 2005

Page 27: MELJUN CORTES Visual basic 2005   02 programming fundamentals

Variable ScopeVariable Scope

Access Modifier Description

Public Public variables are accessible to any code that accesses an instance of the class or structure, or that has access to the type containing the variable. If a class has a public variable, and an instance of that class is accessed from a separate project, application, or component, the public variable is fully accessible to that code.

Protected Protected variables are accessible within the confines of a class and can be used in any code derived from that class, but cannot be accessed outside of the class. Protected variables only apply to classes; they are not available to structures or modules.

Friend Friend variables are accessible anywhere within the assembly, but no further. Instances of a class with a friend variable consumed outside of the assembly hide the variable from that external code. Friend variables can be used in classes, structures, and modules.

Protected Friend Using Protected and Friend together grants that variable all the benefits of both; such variables are accessible within the class and all derived classes, and within the assembly, but not outside of it. Protected Friend variables can only be used in classes, not in structures or modules.

Private Private variables are accessible anywhere within a class, structure, or module, but not outside. They are also hidden from the custom members of derived classes.

PROGRAMMING FUNDAMENTALS 27

Variables, Data Types and Operators

Visual Basic 2005

Page 28: MELJUN CORTES Visual basic 2005   02 programming fundamentals

ConstantsConstants

Constants are essentially read-only variables

Once their value is set in code (at compile time), they cannot change

Constants are defined at the local or module level using the Const keyword:

PROGRAMMING FUNDAMENTALS 28

Variables, Data Types and Operators

<accessModifier> Const <name> As <type> = <value><accessModifier> Const <name> As <type> = <value>

Private Const PI As Single = 3.14159Private Const PI As Single = 3.14159

Visual Basic 2005

Page 29: MELJUN CORTES Visual basic 2005   02 programming fundamentals

EnumeratonsEnumeratons

An enumeration appears as a group of related integer constants

All members of an enumeration share the same data type

PROGRAMMING FUNDAMENTALS 29

Variables, Data Types and Operators

Public Enum VehicleType As Integer bicycle = 2 tricycle = 3 passengerCar = 4 eighteenWheeler = 18 End Enum

Public Enum VehicleType As Integer bicycle = 2 tricycle = 3 passengerCar = 4 eighteenWheeler = 18 End Enum

Dim whatIDrive As VehicleType whatIDrive = VehicleType.passengerCar Dim whatIDrive As VehicleType whatIDrive = VehicleType.passengerCar

Visual Basic 2005

Page 30: MELJUN CORTES Visual basic 2005   02 programming fundamentals

CollectionsCollections

Visual Basic defines an associative array object called a collection

Although similar to an array in that elements appear in a specific order, a collection stores its elements as key-value pairs

PROGRAMMING FUNDAMENTALS 30

Variables, Data Types and Operators

Dim states As New Collection

states.Add("New York", "NY") states.Add("Michigan", "MI")

Dim states As New Collection

states.Add("New York", "NY") states.Add("Michigan", "MI")

Collection object

Visual Basic 2005

Page 31: MELJUN CORTES Visual basic 2005   02 programming fundamentals

CollectionsCollections

Five of the Collection class's members are especially useful:

PROGRAMMING FUNDAMENTALS 31

Variables, Data Types and Operators

Method Description

Add method Adds an item to the collection. Along with the data itself, you can specify an optional key by which the member can be referenced.

Clear method Removes all elements from the collection.

Count property Returns the number of elements in the collection.

Item property Retrieves an element from the collection either by its index (or ordinal position in the collection) or by its key (if provided when the element was added).

Remove method Deletes an element from the collection using the element's index or key.

Visual Basic 2005

Page 32: MELJUN CORTES Visual basic 2005   02 programming fundamentals

OperatorsOperators

Operators are the basic data manipulation tools of any programming language

All data ultimately breaks down into single bits of 0 and 1

The whole reason a computer exists is to manipulate those single bits of data with basic operators

Operators come in two usage types: unary and binary

PROGRAMMING FUNDAMENTALS 32

Variables, Data Types and Operators

Visual Basic 2005

Page 33: MELJUN CORTES Visual basic 2005   02 programming fundamentals

OperatorsOperators

Arithmetic operators

PROGRAMMING FUNDAMENTALS 33

Variables, Data Types and Operators

VB Operation Arithmetic Operator

Algebraic Expression VB Expression

Addition + f + 7 f + 7

Subtraction - p – c p – c

Multiplication * bm b * m

Division (floating point) / x/y or x÷y x / y

Division (integer) \ none v \ u

Modulus Mod r mod s r Mod s

Exponentiation ^ qp q ^ p

Unary minus - -e -e

Unary plus + +g +g

Visual Basic 2005

Page 34: MELJUN CORTES Visual basic 2005   02 programming fundamentals

OperatorsOperators

Concatenation operators

PROGRAMMING FUNDAMENTALS 34

Variables, Data Types and Operators

Operator Description

& (String Concatenation) The string concatenation operator returns a concatenated string from two source string expressions.

+ (Addition) When the addition operator is used with string operands, it concatenates the operands instead of adding their values.

expression1 = “Visual “expression2 = “Basic”result = expression1 & expression2

expression1 = “Visual “expression2 = “Basic”result = expression1 & expression2

Visual Basic 2005

Page 35: MELJUN CORTES Visual basic 2005   02 programming fundamentals

OperatorsOperators

Logical and Bitwise operators

PROGRAMMING FUNDAMENTALS 35

Variables, Data Types and Operators

Operator Description

And The And operator performs a logical or bitwise conjunction on the two source operands. In logical operations, it returns True if and only if both operands evaluate to True.

AndAlso The AndAlso operator works exactly like the logical And operator, but short-circuiting is enabled. AndAlso does not perform bitwise operations.

Or The Or operator performs a logical or bitwise disjunction on the two source operands. In logical operations, it returns True if either of the operands evaluates to True.

OrElse The OrElse operator works exactly like the logical Or operator, but short-circuiting is enabled. OrElse does not perform bitwise operations.

Not The Not operator performs a logical or bitwise negation on a single expression.

Xor The Xor (an abbreviation for "eXclusive OR") operator performs a logical or bitwise exclusion on the two source operands.

<< (Shift left) The << (shift left) operator performs a left shift of the bits in the first operand by the number of bits specified in the second operand.

>> (Shift right) The >> (shift right) operator performs a right shift of the bits in the first operand by the number of bits specified in the second operand.

Visual Basic 2005

Page 36: MELJUN CORTES Visual basic 2005   02 programming fundamentals

OperatorsOperators

Assignment operators

PROGRAMMING FUNDAMENTALS 36

Variables, Data Types and Operators

Operator Description Sample Expression

= Assignment operator x = y + 5

+= Addition assignment operator totalValue += 1

-= Subtraction assignment operator totalValue -= 1

*= Multiplication assignment operator totalValue *= 3

/= Division assignment operator totalValue /= 2

\= Integer division assignment operator totalValue \= 2

^= Exponentiation assignment operator totalValue ^= 2

&= Concatenation assignment operator storyText &= “The End”

<<= Shift left assignment operator dataMask <<= 2

>>= Shift right assignment operator dataMask >> = 2

Visual Basic 2005

Page 37: MELJUN CORTES Visual basic 2005   02 programming fundamentals

OperatorsOperators

Comparison operators

PROGRAMMING FUNDAMENTALS 37

Variables, Data Types and Operators

Standard algebraic equality operator

or relational operator

VB equality or relational

operator

Example of VB condition

Meaning of VB condition

Equality operators

= = x = y x is equal to y

≠ <> x <> y x is not equal to y

Relational operators

> > x > y x is greater than y

< < x < y x is less than y

≥ >= x >= y x is greater than or equal to y

≤ <= x <= y x is less than or equal to y

Visual Basic 2005

Page 38: MELJUN CORTES Visual basic 2005   02 programming fundamentals

OperatorsOperators

The Like Operator◦ The Like operator is used to match a string against a pattern

PROGRAMMING FUNDAMENTALS 38

Variables, Data Types and Operators

If (testString Like "[A-Z]#") Then . . . End If

If (testString Like "[A-Z]#") Then . . . End If

Pattern

Visual Basic 2005

Page 39: MELJUN CORTES Visual basic 2005   02 programming fundamentals

OperatorsOperators

Object operators

PROGRAMMING FUNDAMENTALS 39

Variables, Data Types and Operators

Operator Description Sample Expression

Is The Is operator determines whether two object reference variables refer to the same object instance.

If (customerRecord Is Nothing) Then

IsNot The IsNot operator is equivalent to the Is operator used with the Not logical operator.

If (customerRecord IsNot Nothing) Then

TypeOf The TypeOf operator determines if an object variable is of a specific data type.

If (TypeOf someNumber Is Integer) Then

AddressOf The AddressOf operator returns a procedure delegate that can be used to reference a procedure through a variable.

AddressOf MyCallbackRoutine

GetType The GetType operator returns a System.Type object that contains information about the data type of the operand.

result = GetType(Integer)

Visual Basic 2005

Page 40: MELJUN CORTES Visual basic 2005   02 programming fundamentals

OperatorOperator

Operator precedence

PROGRAMMING FUNDAMENTALS 40

Variables, Data Types and Operators

1. Exponentiation (^).2. Negation (-).3. Multiplication and division (*, /).4. Integer division (\).5. Modulo operator (Mod).6. Addition/concatenation and subtraction (+, -).7. String concatenation (&).8. New in 2003. Arithmetic bit shift (<<, >>).9. Comparison and object operators (=, <>, <, <=, >, >=, Like, Is,

IsNot, TypeOf); the = operator in this list is the Equal To comparison operator, not the assignment operator. New in 2005. The IsNot operator is new in the 2005 release of VB.

10.Logical and bitwise negation (Not).11.Logical and bitwise conjunction (And, AndAlso). New in 2005. The

AndAlso operator is new in the 2005 release of VB.12.Logical and bitwise disjunction (Or, OrElse, Xor). New in 2005. The

OrElse operator is new in the 2005 release of VB.

1. Exponentiation (^).2. Negation (-).3. Multiplication and division (*, /).4. Integer division (\).5. Modulo operator (Mod).6. Addition/concatenation and subtraction (+, -).7. String concatenation (&).8. New in 2003. Arithmetic bit shift (<<, >>).9. Comparison and object operators (=, <>, <, <=, >, >=, Like, Is,

IsNot, TypeOf); the = operator in this list is the Equal To comparison operator, not the assignment operator. New in 2005. The IsNot operator is new in the 2005 release of VB.

10.Logical and bitwise negation (Not).11.Logical and bitwise conjunction (And, AndAlso). New in 2005. The

AndAlso operator is new in the 2005 release of VB.12.Logical and bitwise disjunction (Or, OrElse, Xor). New in 2005. The

OrElse operator is new in the 2005 release of VB.

Visual Basic 2005

Page 41: MELJUN CORTES Visual basic 2005   02 programming fundamentals

Control StatementsControl StatementsObjectives

PROGRAMMING FUNDAMENTALS 41

In this chapter you will learn:•To use the If...Then and If...Then...Else selection statements to choose among alternative actions.•To use the While, Do While...Loop and Do Until...Loop repetition statements to execute statements in a program repeatedly.•To use the compound assignment operators to abbreviate assignment operations.•To use counter-controlled repetition and sentinel-controlled repetition.•To use nested control statements.•To add Visual Basic code to a Windows application.

Visual Basic 2005

Page 42: MELJUN CORTES Visual basic 2005   02 programming fundamentals

OverviewOverview

The 1960s research of Bohm and Jacopini demonstrated that all programs containing GoTo statements could be written without them and that all programs could be written in terms of only three control structures:◦ Sequence structure◦ Selection structure◦ Repetition structure

PROGRAMMING FUNDAMENTALS 42

Control Statements

Visual Basic 2005

Page 43: MELJUN CORTES Visual basic 2005   02 programming fundamentals

Sequence StructureSequence Structure

The code below shows a typical sequence structure:

PROGRAMMING FUNDAMENTALS 43

Control Statements

Input1 = Console.Read()Input2 = Console.Read()

Total = Input1 + Input2

Console.WriteLine(Total)

Input1 = Console.Read()Input2 = Console.Read()

Total = Input1 + Input2

Console.WriteLine(Total)

Visual Basic 2005

Page 44: MELJUN CORTES Visual basic 2005   02 programming fundamentals

Selection StatementsSelection Statements

If..Then Selection Statement◦ A selection statement chooses among alternative courses of action

PROGRAMMING FUNDAMENTALS 44

Control Statements

If studentGrade >= 60 Then Console.WriteLine("Passed") End If

If studentGrade >= 60 Then Console.WriteLine("Passed") End If

Visual Basic 2005

Page 45: MELJUN CORTES Visual basic 2005   02 programming fundamentals

Selection StatementsSelection Statements

If..Then..Else Selection Statement

PROGRAMMING FUNDAMENTALS 45

Control Statements

If studentGrade >= 60 Then Console.WriteLine("Passed")Else Console.WriteLine(“Failed") End If

If studentGrade >= 60 Then Console.WriteLine("Passed")Else Console.WriteLine(“Failed") End If

If studentGrade >= 90 Then Console.WriteLine("A") Else If studentGrade >= 80 Then Console.WriteLine("B") Else If studentGrade >= 70 Then Console.WriteLine("C") Else If studentGrade >= 60 Then Console.WriteLine("D") Else Console.WriteLine("F") End If End If End If End If

If studentGrade >= 90 Then Console.WriteLine("A") Else If studentGrade >= 80 Then Console.WriteLine("B") Else If studentGrade >= 70 Then Console.WriteLine("C") Else If studentGrade >= 60 Then Console.WriteLine("D") Else Console.WriteLine("F") End If End If End If End If

Visual Basic 2005

Page 46: MELJUN CORTES Visual basic 2005   02 programming fundamentals

Selection StatementsSelection Statements

If..Then..Else Selection Statement

PROGRAMMING FUNDAMENTALS 46

Control Statements

If studentGrade >= 90 Then Console.WriteLine("A") ElseIf studentGrade >= 80 Then Console.WriteLine("B") ElseIf studentGrade >= 70 Then Console.WriteLine("C") ElseIf studentGrade >= 60 Then Console.WriteLine("D") Else Console.WriteLine("F") End If

If studentGrade >= 90 Then Console.WriteLine("A") ElseIf studentGrade >= 80 Then Console.WriteLine("B") ElseIf studentGrade >= 70 Then Console.WriteLine("C") ElseIf studentGrade >= 60 Then Console.WriteLine("D") Else Console.WriteLine("F") End If

Visual Basic 2005

Page 47: MELJUN CORTES Visual basic 2005   02 programming fundamentals

Selection StatementsSelection Statements

Select..Case Selection Statement

PROGRAMMING FUNDAMENTALS 47

Control Statements

Select Case studentGrade Case 100 Console.WriteLine(“Perfect Score!") Case 90 To 99 Console.WriteLine("A") Case 80 To 99 Console.WriteLine("B") Case 70 To 79 Console.WriteLine("C") Case 60 To 69 Console.WriteLine("D") Case Else Console.WriteLine("F") End Select

Select Case studentGrade Case 100 Console.WriteLine(“Perfect Score!") Case 90 To 99 Console.WriteLine("A") Case 80 To 99 Console.WriteLine("B") Case 70 To 79 Console.WriteLine("C") Case 60 To 69 Console.WriteLine("D") Case Else Console.WriteLine("F") End Select

Visual Basic 2005

Page 48: MELJUN CORTES Visual basic 2005   02 programming fundamentals

Repetition StatementsRepetition Statements

While..End While Repetition Statement

PROGRAMMING FUNDAMENTALS 48

Control Statements

While product <= 100 Console.Write(product & " " ) product = product * 3 ‘compute next power of 3 End While

While product <= 100 Console.Write(product & " " ) product = product * 3 ‘compute next power of 3 End While

Condition

While block

Visual Basic 2005

Page 49: MELJUN CORTES Visual basic 2005   02 programming fundamentals

Repetition StatementsRepetition Statements

Do While..Loop Repetition Statement

PROGRAMMING FUNDAMENTALS 49

Control Statements

Do While product <= 100 Console.Write(product & " " ) product = product * 3 ‘compute next power of 3 Loop

Do While product <= 100 Console.Write(product & " " ) product = product * 3 ‘compute next power of 3 Loop

Condition

While block

Visual Basic 2005

Page 50: MELJUN CORTES Visual basic 2005   02 programming fundamentals

Repetition StatementsRepetition Statements

Do Until..Loop Repetition Statement

PROGRAMMING FUNDAMENTALS 50

Control Statements

Do Until product > 100 Console.Write(product & " " ) product = product * 3 ‘compute next power of 3 Loop

Do Until product > 100 Console.Write(product & " " ) product = product * 3 ‘compute next power of 3 Loop

Loop will stop only when this condition becomes True

Visual Basic 2005

Page 51: MELJUN CORTES Visual basic 2005   02 programming fundamentals

Repetition StatementsRepetition Statements

For..Next Repetition Statement

PROGRAMMING FUNDAMENTALS 51

Control Statements

' initialization, repetition condition and 6 ' incrementing are all included in For...Next ' statement

For counter As Integer = 2 To 10 Step 2 Console.Write(counter & " " ) Next

' initialization, repetition condition and 6 ' incrementing are all included in For...Next ' statement

For counter As Integer = 2 To 10 Step 2 Console.Write(counter & " " ) Next

counter variable declared within For

Final value of counter variable

Increment value for counter

Initial value of counter

Visual Basic 2005

Page 52: MELJUN CORTES Visual basic 2005   02 programming fundamentals

Repetition StatementsRepetition Statements

Do..Loop While Repetition Statement

PROGRAMMING FUNDAMENTALS 52

Control Statements

' print values 1 to 5 Do Console.Write(counter & " " ) counter += 1 Loop While counter <= 5

' print values 1 to 5 Do Console.Write(counter & " " ) counter += 1 Loop While counter <= 5

Do..Loop While will execute first the statements before testing the condition

Visual Basic 2005

Page 53: MELJUN CORTES Visual basic 2005   02 programming fundamentals

Repetition StatementsRepetition Statements

Do..Loop Until Repetition Statement

PROGRAMMING FUNDAMENTALS 53

Control Statements

' print values 1 to 5 Do Console.Write(counter & " " ) counter += 1 Loop Until counter > 5

' print values 1 to 5 Do Console.Write(counter & " " ) counter += 1 Loop Until counter > 5

Loop will stop only when this condition becomes True

Like Do..Loop While, Do..Loop Until will execute first the statements before testing the condition

Visual Basic 2005

Page 54: MELJUN CORTES Visual basic 2005   02 programming fundamentals

Terminating Repetition StatementsTerminating Repetition Statements

The Exit statement can be used to alter a program's flow of control

Several forms of Exit statement:◦ Exit While◦ Exit Do◦ Exit For

PROGRAMMING FUNDAMENTALS 54

Control Statements

Visual Basic 2005

Page 55: MELJUN CORTES Visual basic 2005   02 programming fundamentals

Terminating Repetition StatementsTerminating Repetition StatementsPROGRAMMING FUNDAMENTALS 55

Control Statements

' exit For...Next statement For counter = 1 To ' skip remaining code in loop only if counter = 5 If counter = 5 Then Exit For ' break out of loop End If Console.Write(counter & " " ) ' output counter Next

' exit For...Next statement For counter = 1 To ' skip remaining code in loop only if counter = 5 If counter = 5 Then Exit For ' break out of loop End If Console.Write(counter & " " ) ' output counter Next

' exit Do Until...Loop statement Do Until counter > 10 ' skip remaining code in loop only if counter = 5 If counter = 5 Then Exit Do ' break out of loop End If Console.Write(counter & " " ) ' output counter counter += 1 ' increment counter Loop

' exit Do Until...Loop statement Do Until counter > 10 ' skip remaining code in loop only if counter = 5 If counter = 5 Then Exit Do ' break out of loop End If Console.Write(counter & " " ) ' output counter counter += 1 ' increment counter Loop

Exit statements

Visual Basic 2005

Page 56: MELJUN CORTES Visual basic 2005   02 programming fundamentals

ExerciseExercisePROGRAMMING FUNDAMENTALS 56

Control Statements

Visual Basic 2005

Page 57: MELJUN CORTES Visual basic 2005   02 programming fundamentals

MethodsMethodsObjectives

PROGRAMMING FUNDAMENTALS 57

In this chapter you will learn:•To construct programs modularly from methods.•That Shared methods are associated with a class rather than a specific instance of the class.•To use common Math methods from the Framework Class Library.•To create new methods.•The mechanisms used to pass information between methods.•How the visibility of identifiers is limited to specific regions of programs.

Visual Basic 2005

Page 58: MELJUN CORTES Visual basic 2005   02 programming fundamentals

OverviewOverview

Experience has shown that the best way to develop and maintain a large program is to construct it from small, simple pieces

This technique is called divide and conquer

PROGRAMMING FUNDAMENTALS 58

Methods

Visual Basic 2005

Page 59: MELJUN CORTES Visual basic 2005   02 programming fundamentals

SubroutinesSubroutines

Subroutines are methods that perform tasks but do not return a value

The format of a subroutine declaration is:

PROGRAMMING FUNDAMENTALS 59

Methods

Sub method-name(parameter-list) declarations and statementsEnd Sub

Sub method-name(parameter-list) declarations and statementsEnd Sub

Visual Basic 2005

Page 60: MELJUN CORTES Visual basic 2005   02 programming fundamentals

SubroutinesSubroutinesPROGRAMMING FUNDAMENTALS 60

Methods

' Subroutine that prints payment information. Module Payment Sub Main() ' call subroutine PrintPay 4 times PrintPay(40, 10.5) PrintPay(38, 21.75) PrintPay(20, 13) PrintPay(30, 14) End Sub ' Main

' print dollar amount earned in console window Sub PrintPay(ByVal hours As Double, _ ByVal wage As Decimal) ' pay = hours * wage Console.WriteLine("The payment is {0:C}", _ hours * wage) End Sub ' PrintPay End Module ' Payment

' Subroutine that prints payment information. Module Payment Sub Main() ' call subroutine PrintPay 4 times PrintPay(40, 10.5) PrintPay(38, 21.75) PrintPay(20, 13) PrintPay(30, 14) End Sub ' Main

' print dollar amount earned in console window Sub PrintPay(ByVal hours As Double, _ ByVal wage As Decimal) ' pay = hours * wage Console.WriteLine("The payment is {0:C}", _ hours * wage) End Sub ' PrintPay End Module ' Payment

Visual Basic 2005

Page 61: MELJUN CORTES Visual basic 2005   02 programming fundamentals

FunctionsFunctions

Functions are methods that return a value to the caller

The format of a function declaration is:

PROGRAMMING FUNDAMENTALS 61

Methods

Function method-name(parameter-list)As return-type declarations and statementsEnd Function

Function method-name(parameter-list)As return-type declarations and statementsEnd Function

Visual Basic 2005

Page 62: MELJUN CORTES Visual basic 2005   02 programming fundamentals

FunctionsFunctionsPROGRAMMING FUNDAMENTALS 62

Methods

‘ Function that squares a number. Module SquareInteger Sub Main() Console.WriteLine(“Number” & vbTab & “Square”)

‘square integers from 1 to 10 For counter As Integer = 1 To 10 Console.WriteLine(counter & vbTab & Square(counter)) Next End Sub ' Main

‘ function Square is executed when it is explicitly called Function Square(ByVal y As Integer) As Integer Return y ^ 2 ‘return square of parameter value End Sub ' Square End Module ' SquareInteger

‘ Function that squares a number. Module SquareInteger Sub Main() Console.WriteLine(“Number” & vbTab & “Square”)

‘square integers from 1 to 10 For counter As Integer = 1 To 10 Console.WriteLine(counter & vbTab & Square(counter)) Next End Sub ' Main

‘ function Square is executed when it is explicitly called Function Square(ByVal y As Integer) As Integer Return y ^ 2 ‘return square of parameter value End Sub ' Square End Module ' SquareInteger

Visual Basic 2005

Page 63: MELJUN CORTES Visual basic 2005   02 programming fundamentals

Shared Methods and Class MathShared Methods and Class Math

Every class provides methods that perform common tasks on objects of the class

Although most methods of a class execute in response to method calls on specific objects

Sometimes a method performs a task that does not depend on the contents of an object

PROGRAMMING FUNDAMENTALS 63

Methods

Visual Basic 2005

Page 64: MELJUN CORTES Visual basic 2005   02 programming fundamentals

Shared Methods and Class MathShared Methods and Class Math

Such a method applies to the class in which it is declared and is known as a Shared method or a Class method

PROGRAMMING FUNDAMENTALS 64

Methods

Console.WriteLine(“Visual Basic”)Console.WriteLine(“Visual Basic”)

WriteLine is a shared method of class Console

Console doesn’t need to be instantiated to use the

WriteLine method

Visual Basic 2005

Page 65: MELJUN CORTES Visual basic 2005   02 programming fundamentals

Shared Methods and Class MathShared Methods and Class MathPROGRAMMING FUNDAMENTALS 65

Methods

Math class methodsMethod Description

Abs(x) returns the absolute value of x

Ceiling(x) rounds x to the smallest integer not less than x

Cos(x) returns the trigonometric cosine of x (x in radians)

Exp(x) returns the exponential ex

Floor(x) rounds x to the largest integer not greater than x

Log(x) returns the natural logarithm of x (base e)

Max(x,y) returns the larger value of x and y (also has versions for Single, Integer and Long values)

Min(x, y) returns the smaller value of x and y (also has versions for Single, Integer and Long values)

Pow(x, y) calculates x raised to the power y (xy)

Sqrt(x) returns the square root of x

Visual Basic 2005

Page 66: MELJUN CORTES Visual basic 2005   02 programming fundamentals

Method Call Stack and Activation Method Call Stack and Activation RecordsRecords

When a program calls a method, the called method must know how to return to the correct location in its caller

The return address in the calling method is pushed onto the method call stack

The successive return addresses are pushed onto the stack in last-in, first-out order so that each method can return to its caller

PROGRAMMING FUNDAMENTALS 66

Methods

Visual Basic 2005

Page 67: MELJUN CORTES Visual basic 2005   02 programming fundamentals

Implicit Argument ConversionImplicit Argument Conversion

An important feature of argument passing is implicit argument conversion converting an argument's value to a type that the method expects to receive in its corresponding parameter

Visual Basic supports both widening and narrowing conversions

PROGRAMMING FUNDAMENTALS 67

Methods

Visual Basic 2005

Page 68: MELJUN CORTES Visual basic 2005   02 programming fundamentals

Implicit Argument ConversionImplicit Argument Conversion

A widening conversion occurs when an argument is converted to a parameter of another type that can hold more data

A narrowing conversion occurs when there is potential for data loss during the conversion

PROGRAMMING FUNDAMENTALS 68

Methods

Console.Write(Math.Sqrt(4))Console.Write(Math.Sqrt(4))

Integer 4 is converted toDouble 4.0 before it ispassed to the Sqrt() procedure

Visual Basic 2005

Page 69: MELJUN CORTES Visual basic 2005   02 programming fundamentals

Implicit Argument ConversionImplicit Argument Conversion

Widening conversions between primitive types

PROGRAMMING FUNDAMENTALS 69

Methods

Type Conversion Types

Boolean Object

Byte Short, Integer, Long, Decimal, Single, Double or Object

Char String or Object

Date Object

Decimal Single, Double or Object

Double Object

Integer Long, Decimal, Single, Double or Object

Long Decimal, Single, Double or Object

Object none

Short Integer, Long, Decimal, Single, Double or Object

Single Double or Object

String Object

Visual Basic 2005

Page 70: MELJUN CORTES Visual basic 2005   02 programming fundamentals

Option Strict and Data Type Option Strict and Data Type ConversionsConversions

Option Strict causes the compiler to check all conversions and requires the programmer to perform an explicit conversion for all narrowing conversions that could cause data loss

PROGRAMMING FUNDAMENTALS 70

Methods

Option Strict option

Visual Basic 2005

Page 71: MELJUN CORTES Visual basic 2005   02 programming fundamentals

Passing ArgumentsPassing Arguments

Arguments are passed in one of two ways:◦ Pass-by-Value◦ Pass-by-Reference

When an argument is passed by value, the program makes a copy of the argument's value and passes the copy to the called method

When argument is passed by reference, the caller gives the called method the ability to access and modify the caller's original data directly

PROGRAMMING FUNDAMENTALS 71

Methods

Visual Basic 2005

Page 72: MELJUN CORTES Visual basic 2005   02 programming fundamentals

Passing ArgumentsPassing Arguments

Sample Program

PROGRAMMING FUNDAMENTALS 72

Methods

Sub Main() Dim data As Integer = 5

ChangeData(data) Console.WriteLine(data)End Sub

Sub ChangeData(ByVal d As integer) d *= 5End Sub

Sub Main() Dim data As Integer = 5

ChangeData(data) Console.WriteLine(data)End Sub

Sub ChangeData(ByVal d As integer) d *= 5End Sub

Sub Main() Dim data As Integer = 5

ChangeData(data) Console.WriteLine(data)End Sub

Sub ChangeData(ByRef d As integer) d *= 5End Sub

Sub Main() Dim data As Integer = 5

ChangeData(data) Console.WriteLine(data)End Sub

Sub ChangeData(ByRef d As integer) d *= 5End Sub

55 2525

A copy of data’s value is given to

parameter d

Address of data’s value is given to

parameter d

ByVal keyword indicates pass-by-

value

ByRef keyword indicates pass-by-

reference

Output: Output:

Variable d points to the address of data

Visual Basic 2005

Page 73: MELJUN CORTES Visual basic 2005   02 programming fundamentals

Method OverloadingMethod Overloading

Visual Basic provides several ways of allowing methods to have variable sets of parameters

Method overloading allows you to create multiple methods with the same name but different signatures

Often, method overloading is used to create several methods with the same name that perform similar tasks on different types of data

PROGRAMMING FUNDAMENTALS 73

Methods

Visual Basic 2005

Page 74: MELJUN CORTES Visual basic 2005   02 programming fundamentals

Method OverloadingMethod Overloading

Sample Program

PROGRAMMING FUNDAMENTALS 74

Methods

‘ Using overloaded methods with identical signatures and ‘ different return types. Module Overload Sub Main() ' call Square methods with Integer and Double Console.WriteLine("The square of Integer 7 is " & _ Square(7) & vbCrLf & _ "The square of Double 7.5 is " & _ Square(7.5)) End Sub ' Main

' method takes a Double and returns an Integer Function Square(ByVal value As Double) As Integer Return Convert.ToInt32(value ^ 2) End Function ' Square

' method takes a Double and returns a Double Function Square(ByVal value As Double) As Double Return value ^ 2 End Function ' Square End Module ' Overload2

‘ Using overloaded methods with identical signatures and ‘ different return types. Module Overload Sub Main() ' call Square methods with Integer and Double Console.WriteLine("The square of Integer 7 is " & _ Square(7) & vbCrLf & _ "The square of Double 7.5 is " & _ Square(7.5)) End Sub ' Main

' method takes a Double and returns an Integer Function Square(ByVal value As Double) As Integer Return Convert.ToInt32(value ^ 2) End Function ' Square

' method takes a Double and returns a Double Function Square(ByVal value As Double) As Double Return value ^ 2 End Function ' Square End Module ' Overload2

Overloaded Square function

Visual Basic 2005

Page 75: MELJUN CORTES Visual basic 2005   02 programming fundamentals

Optional ParametersOptional Parameters

Methods can have optional parametersDeclaring a parameter as optional allows

the calling method to vary the number of arguments to pass

Optional parameters specify a default value that is assigned to the parameter if the optional argument is not passed

PROGRAMMING FUNDAMENTALS 75

Methods

Visual Basic 2005

Page 76: MELJUN CORTES Visual basic 2005   02 programming fundamentals

Optional ParametersOptional Parameters

Declaring optional parameters

PROGRAMMING FUNDAMENTALS 76

Methods

Sub ExampleMethod(ByVal value1 As Boolean, _ Optional ByVal value2 As Integer = 0) . . .End Sub

Sub ExampleMethod(ByVal value1 As Boolean, _ Optional ByVal value2 As Integer = 0) . . .End Sub

Non-optional parameter value1

Optional parameter value2

Optional keyword Default value

ExampleMethod() ExampleMethod(True) ExampleMethod(False, 10)

ExampleMethod() ExampleMethod(True) ExampleMethod(False, 10)

Invalid call

Valid calls

Visual Basic 2005

Page 77: MELJUN CORTES Visual basic 2005   02 programming fundamentals

RecursionRecursion

A recursive method is a method that calls itself either directly or indirectly

The procedure invokes (calls) a fresh copy of itself to work on the smaller problem – this is referred to as a recursive call, or a recursion step

PROGRAMMING FUNDAMENTALS 77

Methods

Visual Basic 2005

Page 78: MELJUN CORTES Visual basic 2005   02 programming fundamentals

RecursionRecursion

Recursive factorial program

PROGRAMMING FUNDAMENTALS 78

Methods

Module Recursion Sub Main() Dim factorialValue As Long

factorialValue = Factorial(5) End Sub

Function Factorial(ByVal number As Integer) As Long If number <= 1 Then ' base case Return 1 Else Return number * Factorial(number - 1) End If End FunctionEnd Module

Module Recursion Sub Main() Dim factorialValue As Long

factorialValue = Factorial(5) End Sub

Function Factorial(ByVal number As Integer) As Long If number <= 1 Then ' base case Return 1 Else Return number * Factorial(number - 1) End If End FunctionEnd Module

Visual Basic 2005

Page 79: MELJUN CORTES Visual basic 2005   02 programming fundamentals

RecursionRecursion

Recursive evaluation of the factorial program

PROGRAMMING FUNDAMENTALS 79

Methods

5!

5 * 4!

4 * 3!

3 * 2!

2 * 1!

1

5!

5 * 4!

4 * 3!

3 * 2!

2 * 1!

1

Final value = 20

5! = 5 * 24 = 120 is returned

4! = 4 * 6 = 24 is returned

3! = 3 * 2 = 6 is returned

2! = 2 * 1 = 2 is returned

1 is returned

(a) Procession of recursive calls (b) Values returned from each recursive call

Visual Basic 2005

Page 80: MELJUN CORTES Visual basic 2005   02 programming fundamentals

ArraysArraysObjectives

PROGRAMMING FUNDAMENTALS 80

In this chapter you will learn:•To use the array data structure; arrays are objects.•How arrays are used to store, sort and search lists and tables of values.•To declare, initialize and refer to individual elements of arrays.•To pass arrays to methods using ByVal and ByRef.•To declare and manipulate multidimensional arrays, especially rectangular arrays and jagged arrays.•To create variable-length parameter lists.•To use the For Each...Next statement to iterate through the elements of arrays without using a loop counter.

Visual Basic 2005

Page 81: MELJUN CORTES Visual basic 2005   02 programming fundamentals

ArraysArrays

Arrays are data structures consisting of data items of the same type

An array is a group of contiguous memory locations that have the same name and the same type

Array names follow the same conventions that apply to other variable names

PROGRAMMING FUNDAMENTALS 81

Arrays

Visual Basic 2005

Page 82: MELJUN CORTES Visual basic 2005   02 programming fundamentals

ArraysArrays

Array consisting of 12 elements

PROGRAMMING FUNDAMENTALS 82

Arrays

-45

78

0

72

1543

-89

0

62

-3

1

6453

6

numberArray(0)

numberArray(1)

numberArray(2)

numberArray(3)

numberArray(4)

numberArray(5)

numberArray(6)

numberArray(7)

numberArray(8)

numberArray(9)

numberArray(10)

numberArray(11)

Name of array(note that all elementsof this array have the

same name, numberArray)

Position number(index or subscript) of

the element withinarray numberArray

Visual Basic 2005

Page 83: MELJUN CORTES Visual basic 2005   02 programming fundamentals

ArraysArrays

Using arrays

PROGRAMMING FUNDAMENTALS 83

Arrays

numberArray(5) = 100numberArray(5) = 100

index1 = 3numberArray(index1 + 5) = 562index1 = 3numberArray(index1 + 5) = 562

sum = numberArray(2) + numberArray(4) + numberArray(6)sum = numberArray(2) + numberArray(4) + numberArray(6)

Assign 100 to sixth element of

numberArray

Assign 562 to ninth element of numberArray

Get the sum of the 3rd, 5th, and 7th element of

numberArray and assign to sum variable

Visual Basic 2005

Page 84: MELJUN CORTES Visual basic 2005   02 programming fundamentals

Declaring and Allocating ArraysDeclaring and Allocating Arrays

Arrays occupy space in memoryThe amount of memory required by an

array depends on the length of the array and the size of the type of the elements in the array

To declare an array, provide the array's name and type

PROGRAMMING FUNDAMENTALS 84

Arrays

Visual Basic 2005

Page 85: MELJUN CORTES Visual basic 2005   02 programming fundamentals

Declaring and Allocating ArraysDeclaring and Allocating Arrays

Declaring an array

PROGRAMMING FUNDAMENTALS 85

Arrays

Dim numberArray As Integer()OrDim numberArray() As Integer

Dim numberArray As Integer()OrDim numberArray() As Integer

numberArray = New Integer(11){}OrnumberArray = New Integer(0 To 11){}

numberArray = New Integer(11){}OrnumberArray = New Integer(0 To 11){}

Allocate 12 elements in

memory

Dim numberArray As New Integer(11){}OrDim numberArray As Integer() = New Integer(11){}

Dim numberArray As New Integer(11){}OrDim numberArray As Integer() = New Integer(11){}

Visual Basic 2005

Page 86: MELJUN CORTES Visual basic 2005   02 programming fundamentals

Declaring and Allocating ArraysDeclaring and Allocating Arrays

Initializing an array

PROGRAMMING FUNDAMENTALS 86

Arrays

Dim numberArray As Integer()numberArray = New Integer(11){1, 2, 3, 4}OrDim numberArray As Integer() = New Integer(11){1, 2, 3, 4}

Dim numberArray As Integer()numberArray = New Integer(11){1, 2, 3, 4}OrDim numberArray As Integer() = New Integer(11){1, 2, 3, 4}

Initial values

Visual Basic 2005

Page 87: MELJUN CORTES Visual basic 2005   02 programming fundamentals

Declaring and Allocating ArraysDeclaring and Allocating Arrays

Sample program

PROGRAMMING FUNDAMENTALS 87

Arrays

‘ Declaring and allocating an array. Module CreateArray Sub Main() Dim array As Integer() ' declare array variable ‘ allocate memory for 10-element array using explicit ‘ array bounds array = New Integer(0 To 9) {}

Console.WriteLine("Index " & vbTab & "Value")

' display values in array For i As Integer = 0 To array.GetUpperBound(0) Console.WriteLine(i & vbTab & array(i)) Next Console.WriteLine(vbCrLf & "The array contains " & _ array.Length & " elements.") End Sub ' Main End Module ' CreateArray

‘ Declaring and allocating an array. Module CreateArray Sub Main() Dim array As Integer() ' declare array variable ‘ allocate memory for 10-element array using explicit ‘ array bounds array = New Integer(0 To 9) {}

Console.WriteLine("Index " & vbTab & "Value")

' display values in array For i As Integer = 0 To array.GetUpperBound(0) Console.WriteLine(i & vbTab & array(i)) Next Console.WriteLine(vbCrLf & "The array contains " & _ array.Length & " elements.") End Sub ' Main End Module ' CreateArray

Visual Basic 2005

Page 88: MELJUN CORTES Visual basic 2005   02 programming fundamentals

Passing an Array to a MethodPassing an Array to a Method

To pass an array argument to a method, specify the name of the array without using parentheses

PROGRAMMING FUNDAMENTALS 88

Arrays

Dim hourlyTemperatures As Integer() = New Integer(24){}

. . .DayData(hourlyTemperatures)

. . .Sub DayData(ByVal tempData As Integer()) . . .End Sub

Dim hourlyTemperatures As Integer() = New Integer(24){}

. . .DayData(hourlyTemperatures)

. . .Sub DayData(ByVal tempData As Integer()) . . .End Sub

hourlyTemperatures Integer array

passes array hourlyTemperatures to method DayData

Method header for DayData

Visual Basic 2005

Page 89: MELJUN CORTES Visual basic 2005   02 programming fundamentals

For Each..Next Repetition StaementFor Each..Next Repetition Staement

Visual Basic provides the For Each...Next repetition statement for iterating through the values in a data structure, such as an array, without using a loop counter

PROGRAMMING FUNDAMENTALS 89

Arrays

. . .Dim gradeArray As Integer() = New Integer() _ {77, 68, 86, 73, 98, 87, 89, 81, 70, 90, 86, 81} Dim lowGrade As Integer = 100

' use For Each...Next to find the minimum grade For Each grade As Integer In gradeArray If grade < lowGrade Then lowGrade = grade End If Next . . .

. . .Dim gradeArray As Integer() = New Integer() _ {77, 68, 86, 73, 98, 87, 89, 81, 70, 90, 86, 81} Dim lowGrade As Integer = 100

' use For Each...Next to find the minimum grade For Each grade As Integer In gradeArray If grade < lowGrade Then lowGrade = grade End If Next . . .

Visual Basic 2005

Page 90: MELJUN CORTES Visual basic 2005   02 programming fundamentals

Multidimensional ArraysMultidimensional Arrays

Often called multiple-subscripted arraysMultidimensional arrays require two or

more indices to identify particular elements

There are two types of multidimensional arrays:◦ rectangular◦ jagged

PROGRAMMING FUNDAMENTALS 90

Arrays

Visual Basic 2005

Page 91: MELJUN CORTES Visual basic 2005   02 programming fundamentals

Multidimensional ArraysMultidimensional Arrays

Rectangular arrays with two indices often are used to represent tables of values consisting of information arranged in rows and columns

PROGRAMMING FUNDAMENTALS 91

Arrays

a(0, 0) a(0, 1) a(0, 2) a(0, 3)

a(1, 0) a(1, 1) a(1, 2) a(1, 3)

a(2, 0) a(2, 1) a(2, 2) a(2, 3)

Column 0 Column 1 Column 2 Column 3

Row 0

Row 1

Row 2

Column index

Row index

Array name

Visual Basic 2005

Page 92: MELJUN CORTES Visual basic 2005   02 programming fundamentals

Multidimensional ArraysMultidimensional Arrays

Declaring and initializing rectangular arrays

PROGRAMMING FUNDAMENTALS 92

Arrays

Dim numbers As Integer(,) = New Integer(1,1) {}

numbers(0, 0) = 1 ' leftmost element in row 0 numbers(0, 1) = 2 ' rightmost element in row 0 numbers(1, 0) = 3 ' leftmost element in row 1 numbers(1, 1) = 4 ' rightmost element in row 1

Or

Dim numbers As Integer(,) = New Integer(,) {{1,2}, {3,4}}

Dim numbers As Integer(,) = New Integer(1,1) {}

numbers(0, 0) = 1 ' leftmost element in row 0 numbers(0, 1) = 2 ' rightmost element in row 0 numbers(1, 0) = 3 ' leftmost element in row 1 numbers(1, 1) = 4 ' rightmost element in row 1

Or

Dim numbers As Integer(,) = New Integer(,) {{1,2}, {3,4}}

1 2

3 4

Column 0 Column 1

Row 0

Row 1

Visual Basic 2005

Page 93: MELJUN CORTES Visual basic 2005   02 programming fundamentals

Multidimensional ArraysMultidimensional Arrays

Jagged arrays are maintained as arrays of arrays

Unlike rectangular arrays, rows in jagged arrays can be of different lengths

PROGRAMMING FUNDAMENTALS 93

Arrays

a(0)(0) a(0)(1) a(0)(2)

a(1)(0) a(1)(1) a(1)(2) a(1)(3)

a(2)(0) a(2)(1)

Row 0

Row 1

Row 2

Col 0 Col 1 Col 2

Col 0 Col 1 Col 2 Col 3

Col 0 Col 1Column index

Row index

Array name

Visual Basic 2005

Page 94: MELJUN CORTES Visual basic 2005   02 programming fundamentals

Multidimensional ArraysMultidimensional Arrays

Declaring and initializing jagged arrays

PROGRAMMING FUNDAMENTALS 94

Arrays

' create jagged array Dim array1 As Integer()() = New Integer(2)(){} ' three rows

array1(0) = New Integer() {1, 2} ' row 0 is a single array array1(1) = New Integer() {3} ' row 1 is a single array array1(2) = New Integer() {4, 5, 6} ' row 2 is a single array

' create jagged array Dim array1 As Integer()() = New Integer(2)(){} ' three rows

array1(0) = New Integer() {1, 2} ' row 0 is a single array array1(1) = New Integer() {3} ' row 1 is a single array array1(2) = New Integer() {4, 5, 6} ' row 2 is a single array

1 2

3

4 5

Row 0

Row 1

Row 2

Col 0 Col 1

Col 0

Col 0 Col 1

6

Col 2

Visual Basic 2005

Page 95: MELJUN CORTES Visual basic 2005   02 programming fundamentals

Multidimensional ArraysMultidimensional Arrays

Sample Program

PROGRAMMING FUNDAMENTALS 95

Arrays

' Initializing a jagged array. Module JaggedArray Sub Main() ' create jagged array Dim array1 As Integer()() = New Integer(2)(){}' three rows array1(0) = New Integer() {1, 2} ' row 0 is a single array array1(1) = New Integer() {3} ' row 1 is a single array array1(2) = New Integer() {4, 5, 6} ' row 2 is a single array

Console.WriteLine("Values in jagged array1 by row are")

' output array1 elements For i As Integer = 0 To array1.GetUpperBound(0) For j As Integer = 0 To array1(i).GetUpperBound(0) Console.Write(array1(i)(j) & " ") Next Console.WriteLine() Next End Sub ' Main End Module ' JaggedArray

' Initializing a jagged array. Module JaggedArray Sub Main() ' create jagged array Dim array1 As Integer()() = New Integer(2)(){}' three rows array1(0) = New Integer() {1, 2} ' row 0 is a single array array1(1) = New Integer() {3} ' row 1 is a single array array1(2) = New Integer() {4, 5, 6} ' row 2 is a single array

Console.WriteLine("Values in jagged array1 by row are")

' output array1 elements For i As Integer = 0 To array1.GetUpperBound(0) For j As Integer = 0 To array1(i).GetUpperBound(0) Console.Write(array1(i)(j) & " ") Next Console.WriteLine() Next End Sub ' Main End Module ' JaggedArray

Visual Basic 2005

Page 96: MELJUN CORTES Visual basic 2005   02 programming fundamentals

Variable-Length Parameter ListVariable-Length Parameter List

It is possible to create methods that receive a variable number of arguments, using keyword ParamArray

PROGRAMMING FUNDAMENTALS 96

Arrays

. . .Sub Main AnyNumberOfArguments() AnyNumberOfArguments(2, 3) AnyNumberOfArguments(7, 8, 9, 10, 11, 12)End Sub

Sub AnyNumberOfArguments(ByVal ParamArray array1 As Integer()) . . . End Sub. . .

. . .Sub Main AnyNumberOfArguments() AnyNumberOfArguments(2, 3) AnyNumberOfArguments(7, 8, 9, 10, 11, 12)End Sub

Sub AnyNumberOfArguments(ByVal ParamArray array1 As Integer()) . . . End Sub. . .

ParamArray keyword

Visual Basic 2005

Page 97: MELJUN CORTES Visual basic 2005   02 programming fundamentals

The ReDim StatementThe ReDim Statement

The number of elements in an array can be changed at execution time

The ReDim statement enables you to dynamically change the array size, but not the type of the array elements, nor the number of dimensions in the array

PROGRAMMING FUNDAMENTALS 97

Arrays

Visual Basic 2005

Page 98: MELJUN CORTES Visual basic 2005   02 programming fundamentals

The ReDim StatementThe ReDim Statement

Using ReDim statements to change the array size

PROGRAMMING FUNDAMENTALS 98

Arrays

. . .Dim array As Integer() = {1, 2, 3, 4, 5} Dim arrayCopy As Integer() = array

. . .' change the size of the array without the Preserve keyword ReDim array(6)

. . .' change the size of the array with the Preserve keyword ReDim Preserve arrayCopy(6) arrayCopy(6) = 7 ' assign 7 to array element 6

. . .Dim array As Integer() = {1, 2, 3, 4, 5} Dim arrayCopy As Integer() = array

. . .' change the size of the array without the Preserve keyword ReDim array(6)

. . .' change the size of the array with the Preserve keyword ReDim Preserve arrayCopy(6) arrayCopy(6) = 7 ' assign 7 to array element 6

Preserve keyword preserves the content of the

array

Visual Basic 2005

Page 99: MELJUN CORTES Visual basic 2005   02 programming fundamentals

Passing Arrays: ByVal vs ByRefPassing Arrays: ByVal vs ByRef

A variable that "stores" an object, such as an array, does not actually store the object itself

Instead, the variable stores a reference to the object

The distinction between value-type variables and reference-type variables raises some subtle issues that you must understand to create secure, stable programs

PROGRAMMING FUNDAMENTALS 99

Arrays

Visual Basic 2005

Page 100: MELJUN CORTES Visual basic 2005   02 programming fundamentals

ExerciseExercisePROGRAMMING FUNDAMENTALS 100

Page 101: MELJUN CORTES Visual basic 2005   02 programming fundamentals

End of Programming End of Programming FundamentalsFundamentals

PROGRAMMING FUNDAMENTALS 101