• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
MELJUN CORTES Visual Basic 2005  Programming Fundamentals
 

MELJUN CORTES Visual Basic 2005 Programming Fundamentals

on

  • 292 views

MELJUN CORTES Visual Basic 2005 Programming Fundamentals

MELJUN CORTES Visual Basic 2005 Programming Fundamentals

Statistics

Views

Total Views
292
Views on SlideShare
292
Embed Views
0

Actions

Likes
0
Downloads
13
Comments
0

0 Embeds 0

No embeds

Accessibility

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    MELJUN CORTES Visual Basic 2005  Programming Fundamentals MELJUN CORTES Visual Basic 2005 Programming Fundamentals Presentation Transcript

    • Visual Basic 2005 II. PROGRAMMING FUNDAMENTALS MELJUN CORTES
    • 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. Variables, Data Types and Operators Objectives PROGRAMMING FUNDAMENTALS Visual Basic 2005 2
    • Variables, Data Types and Operators 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 Overview PROGRAMMING FUNDAMENTALS Visual Basic 2005 3
    • Variables, Data Types and Operators 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 Data Types PROGRAMMING FUNDAMENTALS Visual Basic 2005 4
    • Variables, Data Types and Operators 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 Data Types PROGRAMMING FUNDAMENTALS Visual Basic 2005 5
    • Variables, Data Types and Operators 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 Dim usesInt32 As Integer MessageBox.Show(usesInt32.MaxValue) ' Displays 2147483647 MessageBox.Show(usesInt32.MaxValue) ' Displays 2147483647 Data Types PROGRAMMING FUNDAMENTALS Visual Basic 2005 6
    • Variables, Data Types and Operators 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 Value and Reference Types PROGRAMMING FUNDAMENTALS Visual Basic 2005 7
    • Variables, Data Types and Operators Dim simpleValue As Integer = 5 Dim simpleValue As Integer = 5 SimpleValue 5 A variable (SimpleValue) of a value type (Integer) contains a value (5) of that type Dim somewhereElse As New MyCustomClass Dim somewhereElse As New MyCustomClass somewhereElse MyCustomClass customValue (The arrow represents the memory address of the MyCustomClass object) A variable (somewhereElse) of a reference type (MyCustomClass) contains a reference (memory address) to an object of that type Value and Reference Types PROGRAMMING FUNDAMENTALS Visual Basic 2005 8
    • Variables, Data Types and Operators 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 VB Data Types PROGRAMMING FUNDAMENTALS Visual Basic 2005 9
    • Variables, Data Types and Operators 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. VB Data Types PROGRAMMING FUNDAMENTALS Visual Basic 2005 10
    • Variables, Data Types and Operators 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… VB Data Types PROGRAMMING FUNDAMENTALS Visual Basic 2005 11
    • Variables, Data Types and Operators Type Size in Bytes Value Range Single 4 negative range: 3.4028235E+38 to 1.401298E-45 positive 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.94065645841246544E324 positive 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 String 16 Depends on platform Range with no decimal point: ±79,228,162,514,264,337,593,543,950,335 Range with 28 places to the right of the decimal point: ±7.9228162514264337593543950335 The smallest nonzero number is: ±0.0000000000000000000000000001 (±1E28) up to approximately 2 billion Unicode characters VB Data Types PROGRAMMING FUNDAMENTALS Visual Basic 2005 12
    • Variables, Data Types and Operators These user-defined data types extend the basic data types with new types of your own choosing Structures can be used to define userdefined types [Public|Private|Friend] Structure structureName [Public|Private|Friend] Structure structureName member declarations member declarations End Structure End Structure User-defined Data Types PROGRAMMING FUNDAMENTALS Visual Basic 2005 13
    • Variables, Data Types and Operators The simplest and most common use of structures is to encapsulate related variables, or fields Structure Person Structure Person Public Name As String Public Name As String Public Address As String Public Address As String Public City As String Public City As String Public State As String Public State As String Public Zip As String Public Zip As String Public Age As Short Public Age As Short End Structure End Structure User-defined Data Types PROGRAMMING FUNDAMENTALS Visual Basic 2005 14
    • Variables, Data Types and Operators A standard declaration defines a variable of type Person: Dim onePerson As Person Dim onePerson As Person Members of the structure are accessed using the standard "dot" syntax that applies also to classes: onePerson.name = “Beethoven” onePerson.name = “Beethoven” User-defined Data Types PROGRAMMING FUNDAMENTALS Visual Basic 2005 15
    • Variables, Data Types and Operators 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 Data Type Conversion PROGRAMMING FUNDAMENTALS Visual Basic 2005 16
    • Variables, Data Types and Operators Casts and conversions can be widening or narrowing Dim miniSize As Byte = 6 Dim miniSize As Byte = 6 Dim superSize As Long Dim superSize As Long superSize = CLng(miniSize) ' Convert Byte variable to Long superSize = CLng(miniSize) ' Convert Byte variable to Long superSize = CLng("12") ' Convert String literal to Long superSize = CLng("12") ' Convert String literal to Long Dim smallerData As Integer = 3948 Dim smallerData As Integer = 3948 Dim largerData As Long Dim largerData As Long largerData = smallerData largerData = smallerData Data Type Conversion PROGRAMMING FUNDAMENTALS Visual Basic 2005 17
    • Variables, Data Types and Operators Visual Basic includes conversion functions for the basic data types: 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. Data Type Conversion PROGRAMMING FUNDAMENTALS Visual Basic 2005 18
    • 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. Data Type Conversion PROGRAMMING FUNDAMENTALS Visual Basic 2005 19
    • Variables, Data Types and Operators A variable can be defined as an entity that has the following six properties: ◦ ◦ ◦ ◦ ◦ ◦ Name Address Data type Value Scope Lifetime Variables PROGRAMMING FUNDAMENTALS Visual Basic 2005 20
    • Variables, Data Types and Operators A variable declaration is an association of a variable name with a data type Dim createMeNow As Integer Dim createMeNow As Integer Dim createMeNow As Integer = New Integer Dim createMeNow As Integer = New Integer Dim createMeNow As New Integer Dim createMeNow As New Integer Variables PROGRAMMING FUNDAMENTALS Visual Basic 2005 21
    • Variables, Data Types and Operators 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 procedurelevel scope Variable Scope PROGRAMMING FUNDAMENTALS Visual Basic 2005 22
    • Variables, Data Types and Operators These local variables often appear immediately upon entering the code of the procedure Public Public Dim Dim Dim Dim Sub DoTheWork( ) Sub DoTheWork( ) localInt As Integer localInt As Integer localEmp As New Employee localEmp As New Employee . . . . . . End Sub End Sub Local variables Variable Scope PROGRAMMING FUNDAMENTALS Visual Basic 2005 23
    • Variables, Data Types and Operators  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 Public Sub DoTheWork(ByVal fromWhen As Date, ByVal howMuch As Decimal) Public Sub DoTheWork(ByVal fromWhen As Date, ByVal howMuch As Decimal) If (fromWhen < Today) Then If (fromWhen < Today) Then ' ----- This variable is available within the outer-most ' ----- This variable is available within the outer-most ' If block, which also includes the inner-most block. ' If block, which also includes the inner-most block. ' It is not available outside the outer-most If block. ' It is not available outside the outer-most If block. Dim simpleCalculation As Integer Dim simpleCalculation As Integer If (howMuch > 0) Then If (howMuch > 0) Then ' ----- This variable is only available within the ' ----- This variable is only available within the ' inner-most If block. ' inner-most If block. Dim complexCalculation As Integer Dim complexCalculation As Integer End If End If End If End If End Sub End Sub Variable Scope PROGRAMMING FUNDAMENTALS Visual Basic 2005 24
    • Variables, Data Types and Operators Local variables can extend their lifetime beyond the execution timeline of the procedure in which they reside by declaring them Static Static longLasting As Integer = 0 Static longLasting As Integer = 0 Static keyword Variable Scope PROGRAMMING FUNDAMENTALS Visual Basic 2005 25
    • Variables, Data Types and Operators All variables declared within a class (or structure or module), but outside of any procedure within that class, have typelevel scope However, the scope of these variables can go beyond the type level through the use of an access modifier Variable Scope PROGRAMMING FUNDAMENTALS Visual Basic 2005 26
    • Variables, Data Types and Operators 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. Variable Scope PROGRAMMING FUNDAMENTALS Visual Basic 2005 27
    • Variables, Data Types and Operators 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: <accessModifier> Const <name> As <type> = <value> <accessModifier> Const <name> As <type> = <value> Private Const PI As Single = 3.14159 Private Const PI As Single = 3.14159 Constants PROGRAMMING FUNDAMENTALS Visual Basic 2005 28
    • Variables, Data Types and Operators An enumeration appears as a group of related integer constants All members of an enumeration share the same data type Public Enum VehicleType As Integer Public Enum VehicleType As Integer bicycle = 2 bicycle = 2 tricycle = 3 tricycle = 3 passengerCar = 4 passengerCar = 4 eighteenWheeler = 18 eighteenWheeler = 18 End Enum End Enum Dim whatIDrive As VehicleType Dim whatIDrive As VehicleType whatIDrive = VehicleType.passengerCar whatIDrive = VehicleType.passengerCar Enumeratons PROGRAMMING FUNDAMENTALS Visual Basic 2005 29
    • Variables, Data Types and Operators 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 Dim states As New Collection Dim states As New Collection states.Add("New York", states.Add("New York", states.Add("Michigan", states.Add("Michigan", "NY") "NY") "MI") "MI") Collection object Collections PROGRAMMING FUNDAMENTALS Visual Basic 2005 30
    • Variables, Data Types and Operators Five of the Collection class's members are especially useful: 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. Collections PROGRAMMING FUNDAMENTALS Visual Basic 2005 31
    • Variables, Data Types and Operators 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 Operators PROGRAMMING FUNDAMENTALS Visual Basic 2005 32
    • Variables, Data Types and Operators Arithmetic VB Operation operators 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 vu Mod r mod s r Mod s Exponentiation ^ qp q^p Unary minus - -e -e Unary plus + +g +g Modulus Operators PROGRAMMING FUNDAMENTALS Visual Basic 2005 33
    • Variables, Data Types and Operators Concatenation 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 “ expression1 = “Visual “ expression2 = “Basic” expression2 = “Basic” result = expression1 & expression2 result = expression1 & expression2 Operators PROGRAMMING FUNDAMENTALS Visual Basic 2005 34
    • Variables, Data Types and Operators Logical and Bitwise 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 OrElse 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. The OrElse operator works exactly like the logical Or operator, but shortcircuiting 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. Operators PROGRAMMING FUNDAMENTALS Visual Basic 2005 35
    • Variables, Data Types and Operators Assignment Operator = operators 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 Operators PROGRAMMING FUNDAMENTALS Visual Basic 2005 36
    • Variables, Data Types and Operators Comparison Standard algebraic equality operator or relational operator operators VB equality or relational operator Example of VB condition Meaning of VB condition = = x=y ≠ <> x <> y x is not equal to y > > 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 Equality operators x is equal to y Relational operators Operators PROGRAMMING FUNDAMENTALS Visual Basic 2005 37
    • Variables, Data Types and Operators The Like Operator ◦ The Like operator is used to match a string against a pattern If (testString Like "[A-Z]#") Then If (testString Like "[A-Z]#") Then . . . . . . End If End If Pattern Operators PROGRAMMING FUNDAMENTALS Visual Basic 2005 38
    • Variables, Data Types and Operators Object 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) Operators PROGRAMMING FUNDAMENTALS Visual Basic 2005 39
    • Variables, Data Types and Operators Operator precedence 1. 1. 2. 2. 3. 3. 4. 4. 5. 5. 6. 6. 7. 7. 8. 8. 9. 9. Exponentiation (^). Exponentiation (^). Negation (-). Negation (-). Multiplication and division (*, /). Multiplication and division (*, /). Integer division (). Integer division (). Modulo operator (Mod). Modulo operator (Mod). Addition/concatenation and subtraction (+, -). Addition/concatenation and subtraction (+, -). String concatenation (&). String concatenation (&). New in 2003. Arithmetic bit shift (<<, >>). New in 2003. Arithmetic bit shift (<<, >>). Comparison and object operators (=, <>, <, <=, >, >=, Like, Is, Comparison and object operators (=, <>, <, <=, >, >=, Like, Is, IsNot, TypeOf); the = operator in this list is the Equal To IsNot, TypeOf); the = operator in this list is the Equal To comparison operator, not the assignment operator. New in 2005. comparison operator, not the assignment operator. New in 2005. The IsNot operator is new in the 2005 release of VB. The IsNot operator is new in the 2005 release of VB. 10.Logical and bitwise negation (Not). 10.Logical and bitwise negation (Not). 11.Logical and bitwise conjunction (And, AndAlso). New in 2005. The 11.Logical and bitwise conjunction (And, AndAlso). New in 2005. The AndAlso operator is new in the 2005 release of VB. AndAlso operator is new in the 2005 release of VB. 12.Logical and bitwise disjunction (Or, OrElse, Xor). New in 2005. The 12.Logical and bitwise disjunction (Or, OrElse, Xor). New in 2005. The OrElse operator is new in the 2005 release of VB. OrElse operator is new in the 2005 release of VB. Operator PROGRAMMING FUNDAMENTALS Visual Basic 2005 40
    • 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. Control Statements Objectives PROGRAMMING FUNDAMENTALS Visual Basic 2005 41
    • Control Statements 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 Overview PROGRAMMING FUNDAMENTALS Visual Basic 2005 42
    • Control Statements The code below shows a typical sequence structure: Input1 = Console.Read() Input1 = Console.Read() Input2 = Console.Read() Input2 = Console.Read() Total = Input1 + Input2 Total = Input1 + Input2 Console.WriteLine(Total) Console.WriteLine(Total) Sequence Structure PROGRAMMING FUNDAMENTALS Visual Basic 2005 43
    • Control Statements If..Then Selection Statement ◦ A selection statement chooses among alternative courses of action If studentGrade >= 60 Then If studentGrade >= 60 Then Console.WriteLine("Passed") Console.WriteLine("Passed") End If End If Selection Statements PROGRAMMING FUNDAMENTALS Visual Basic 2005 44
    • Control Statements If..Then..Else Selection Statement If studentGrade >= 60 Then If studentGrade >= 60 Then Console.WriteLine("Passed") Console.WriteLine("Passed") Else Else Console.WriteLine(“Failed") Console.WriteLine(“Failed") End If End If If studentGrade >= 90 Then If studentGrade >= 90 Then Console.WriteLine("A") Console.WriteLine("A") Else Else If studentGrade >= 80 Then If studentGrade >= 80 Then Console.WriteLine("B") Console.WriteLine("B") Else Else If studentGrade >= 70 Then If studentGrade >= 70 Then Console.WriteLine("C") Console.WriteLine("C") Else Else If studentGrade >= 60 Then If studentGrade >= 60 Then Console.WriteLine("D") Console.WriteLine("D") Else Else Console.WriteLine("F") Console.WriteLine("F") End If End If End If End If End If End If End If End If Selection Statements PROGRAMMING FUNDAMENTALS Visual Basic 2005 45
    • Control Statements If..Then..Else Selection Statement If studentGrade >= 90 Then If studentGrade >= 90 Then Console.WriteLine("A") Console.WriteLine("A") ElseIf studentGrade >= 80 Then ElseIf studentGrade >= 80 Then Console.WriteLine("B") Console.WriteLine("B") ElseIf studentGrade >= 70 Then ElseIf studentGrade >= 70 Then Console.WriteLine("C") Console.WriteLine("C") ElseIf studentGrade >= 60 Then ElseIf studentGrade >= 60 Then Console.WriteLine("D") Console.WriteLine("D") Else Else Console.WriteLine("F") Console.WriteLine("F") End If End If Selection Statements PROGRAMMING FUNDAMENTALS Visual Basic 2005 46
    • Control Statements Select..Case Selection Statement Select Case studentGrade Select Case studentGrade Case 100 Case 100 Console.WriteLine(“Perfect Score!") Console.WriteLine(“Perfect Score!") Case 90 To 99 Case 90 To 99 Console.WriteLine("A") Console.WriteLine("A") Case 80 To 99 Case 80 To 99 Console.WriteLine("B") Console.WriteLine("B") Case 70 To 79 Case 70 To 79 Console.WriteLine("C") Console.WriteLine("C") Case 60 To 69 Case 60 To 69 Console.WriteLine("D") Console.WriteLine("D") Case Else Case Else Console.WriteLine("F") Console.WriteLine("F") End Select End Select Selection Statements PROGRAMMING FUNDAMENTALS Visual Basic 2005 47
    • Control Statements While..End While Repetition Statement Condition While block While product <= 100 While product <= 100 Console.Write(product & " " ) Console.Write(product & " " ) product = product * 3 ‘compute next power of 3 product = product * 3 ‘compute next power of 3 End While End While Repetition Statements PROGRAMMING FUNDAMENTALS Visual Basic 2005 48
    • Control Statements Do While..Loop Repetition Statement Condition While block Do While product <= 100 Do While product <= 100 Console.Write(product & " " ) Console.Write(product & " " ) product = product * 3 ‘compute next power of 3 product = product * 3 ‘compute next power of 3 Loop Loop Repetition Statements PROGRAMMING FUNDAMENTALS Visual Basic 2005 49
    • Control Statements Do Until..Loop Repetition Statement Loop will stop only when this condition becomes True Do Until product > 100 Do Until product > 100 Console.Write(product & " " ) Console.Write(product & " " ) product = product * 3 ‘compute next power of 3 product = product * 3 ‘compute next power of 3 Loop Loop Repetition Statements PROGRAMMING FUNDAMENTALS Visual Basic 2005 50
    • Control Statements For..Next Repetition Statement Final value of counter variable counter variable declared within For ' ' ' ' ' ' Increment value for counter initialization, repetition condition and 6 initialization, repetition condition and 6 incrementing are all included in For...Next incrementing are all included in For...Next statement statement For counter As Integer = 2 To 10 Step 2 For counter As Integer = 2 To 10 Step 2 Console.Write(counter & " " ) Console.Write(counter & " " ) Next Next Initial value of counter Repetition Statements PROGRAMMING FUNDAMENTALS Visual Basic 2005 51
    • Control Statements Do..Loop Do..Loop While will execute first the statements before testing the condition While Repetition Statement ' print values 1 to 5 ' print values 1 to 5 Do Do Console.Write(counter & " " ) Console.Write(counter & " " ) counter += 1 counter += 1 Loop While counter <= 5 Loop While counter <= 5 Repetition Statements PROGRAMMING FUNDAMENTALS Visual Basic 2005 52
    • Control Statements Do..Loop Like Do..Loop While, Do..Loop Until will execute first the statements before testing the condition Until Repetition Statement ' print values 1 to 5 ' print values 1 to 5 Do Do Console.Write(counter & " " ) Console.Write(counter & " " ) counter += 1 counter += 1 Loop Until counter > 5 Loop Until counter > 5 Loop will stop only when this condition becomes True Repetition Statements PROGRAMMING FUNDAMENTALS Visual Basic 2005 53
    • Control 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 Terminating Repetition Statements PROGRAMMING FUNDAMENTALS Visual Basic 2005 54
    • Control Statements Exit statements ' exit For...Next statement ' exit For...Next statement For counter = 1 To For counter = 1 To ' skip remaining code in loop only if counter = 5 ' skip remaining code in loop only if counter = 5 If counter = 5 Then If counter = 5 Then Exit For ' break out of loop Exit For ' break out of loop End If End If Console.Write(counter & " " ) ' output counter Console.Write(counter & " " ) ' output counter Next Next ' exit Do Until...Loop statement ' exit Do Until...Loop statement Do Until counter > 10 Do Until counter > 10 ' skip remaining code in loop only if counter = 5 ' skip remaining code in loop only if counter = 5 If counter = 5 Then If counter = 5 Then Exit Do ' break out of loop Exit Do ' break out of loop End If End If Console.Write(counter & " " ) ' output counter Console.Write(counter & " " ) ' output counter counter += 1 ' increment counter counter += 1 ' increment counter Loop Loop Terminating Repetition Statements PROGRAMMING FUNDAMENTALS Visual Basic 2005 55
    • Control Statements Exercise PROGRAMMING FUNDAMENTALS Visual Basic 2005 56
    • 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. Methods Objectives PROGRAMMING FUNDAMENTALS Visual Basic 2005 57
    • Methods 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 Overview PROGRAMMING FUNDAMENTALS Visual Basic 2005 58
    • Methods Subroutines are methods that perform tasks but do not return a value The format of a subroutine declaration is: Sub method-name(parameter-list) Sub method-name(parameter-list) declarations and statements declarations and statements End Sub End Sub Subroutines PROGRAMMING FUNDAMENTALS Visual Basic 2005 59
    • Methods ' Subroutine that prints payment information. ' Subroutine that prints payment information. Module Payment Module Payment Sub Main() Sub Main() ' call subroutine PrintPay 4 times ' call subroutine PrintPay 4 times PrintPay(40, 10.5) PrintPay(40, 10.5) PrintPay(38, 21.75) PrintPay(38, 21.75) PrintPay(20, 13) PrintPay(20, 13) PrintPay(30, 14) PrintPay(30, 14) End Sub ' Main End Sub ' Main ' print dollar amount earned in console window ' print dollar amount earned in console window Sub PrintPay(ByVal hours As Double, _ Sub PrintPay(ByVal hours As Double, _ ByVal wage As Decimal) ByVal wage As Decimal) ' pay = hours * wage ' pay = hours * wage Console.WriteLine("The payment is {0:C}", _ Console.WriteLine("The payment is {0:C}", _ hours * wage) hours * wage) End Sub ' PrintPay End Sub ' PrintPay End Module ' Payment End Module ' Payment Subroutines PROGRAMMING FUNDAMENTALS Visual Basic 2005 60
    • Methods Functions are methods that return a value to the caller The format of a function declaration is: Function method-name(parameter-list)As return-type Function method-name(parameter-list)As return-type declarations and statements declarations and statements End Function End Function Functions PROGRAMMING FUNDAMENTALS Visual Basic 2005 61
    • Methods ‘ Function that squares a number. ‘ Function that squares a number. Module SquareInteger Module SquareInteger Sub Main() Sub Main() Console.WriteLine(“Number” & vbTab & “Square”) Console.WriteLine(“Number” & vbTab & “Square”) ‘square integers from 1 to 10 ‘square integers from 1 to 10 For counter As Integer = 1 To 10 For counter As Integer = 1 To 10 Console.WriteLine(counter & vbTab & Square(counter)) Console.WriteLine(counter & vbTab & Square(counter)) Next Next End Sub ' Main End Sub ' Main ‘ function Square is executed when it is explicitly called ‘ function Square is executed when it is explicitly called Function Square(ByVal y As Integer) As Integer Function Square(ByVal y As Integer) As Integer Return y ^ 2 ‘return square of parameter value Return y ^ 2 ‘return square of parameter value End Sub ' Square End Sub ' Square End Module ' SquareInteger End Module ' SquareInteger Functions PROGRAMMING FUNDAMENTALS Visual Basic 2005 62
    • Methods 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 Shared Methods and Class Math PROGRAMMING FUNDAMENTALS Visual Basic 2005 63
    • Methods Such a method applies to the class in which it is declared and is known as a Shared method or a Class method 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 Shared Methods and Class Math PROGRAMMING FUNDAMENTALS Visual Basic 2005 64
    • Methods Math class methods Method 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 Shared Methods and Class Math PROGRAMMING FUNDAMENTALS Visual Basic 2005 65
    • Methods 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 Method Call Stack and Activation Records PROGRAMMING FUNDAMENTALS Visual Basic 2005 66
    • Methods 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 Implicit Argument Conversion PROGRAMMING FUNDAMENTALS Visual Basic 2005 67
    • Methods 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 Console.Write(Math.Sqrt(4)) Console.Write(Math.Sqrt(4)) Integer 4 is converted to Double 4.0 before it is passed to the Sqrt() procedure Implicit Argument Conversion PROGRAMMING FUNDAMENTALS Visual Basic 2005 68
    • Methods Widening types conversions between primitive 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 Implicit Argument Conversion PROGRAMMING FUNDAMENTALS Visual Basic 2005 69
    • Methods 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 Option Strict option Option Strict and Data Type Conversions PROGRAMMING FUNDAMENTALS Visual Basic 2005 70
    • Methods 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 Passing Arguments PROGRAMMING FUNDAMENTALS Visual Basic 2005 71
    • Methods Sample Program Sub Main() Sub Main() Dim data As Integer = 5 Dim data As Integer = 5 ChangeData(data) ChangeData(data) Console.WriteLine(data) Console.WriteLine(data) End Sub End Sub Sub Main() Sub Main() Dim data As Integer = 5 Dim data As Integer = 5 A copy of data’s value is given to parameter d Address of data’s value is given to parameter d ChangeData(data) ChangeData(data) Console.WriteLine(data) Console.WriteLine(data) End Sub End Sub Sub ChangeData(ByVal d As integer) Sub ChangeData(ByVal d As integer) d *= 5 d *= 5 End Sub End Sub Sub ChangeData(ByRef d As integer) Sub ChangeData(ByRef d As integer) d *= 5 d *= 5 End Sub End Sub Output: Output: 5 5 25 25 ByVal keyword indicates pass-byvalue Variable d points to the address of data ByRef keyword indicates pass-byreference Passing Arguments PROGRAMMING FUNDAMENTALS Visual Basic 2005 72
    • Methods 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 Method Overloading PROGRAMMING FUNDAMENTALS Visual Basic 2005 73
    • Methods Sample Program ‘ Using overloaded methods with identical signatures and ‘ Using overloaded methods with identical signatures and ‘ different return types. ‘ different return types. Module Overload Module Overload Sub Main() ' call Square methods with Integer and Double Sub Main() ' call Square methods with Integer and Double Console.WriteLine("The square of Integer 7 is " & _ Console.WriteLine("The square of Integer 7 is " & _ Square(7) & vbCrLf & _ Square(7) & vbCrLf & _ "The square of Double 7.5 is " & _ "The square of Double 7.5 is " & _ End Sub ' Main End Sub ' Main Square(7.5)) Square(7.5)) ' method takes a Double and returns an Integer ' method takes a Double and returns an Integer Function Square(ByVal value As Double) As Integer Function Square(ByVal value As Double) As Integer Return Convert.ToInt32(value ^ 2) Return Convert.ToInt32(value ^ 2) End Function ' Square End Function ' Square Overloaded Square function ' method takes a Double and returns a Double ' method takes a Double and returns a Double Function Square(ByVal value As Double) As Double Function Square(ByVal value As Double) As Double Return value ^ 2 Return value ^ 2 End Function ' Square End Function ' Square End Module ' Overload2 End Module ' Overload2 Method Overloading PROGRAMMING FUNDAMENTALS Visual Basic 2005 74
    • Methods Methods can have optional parameters Declaring 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 Optional Parameters PROGRAMMING FUNDAMENTALS Visual Basic 2005 75
    • Methods Declaring optional parameters Non-optional parameter value1 Sub ExampleMethod(ByVal value1 As Boolean, Sub ExampleMethod(ByVal value1 As Boolean, Optional ByVal value2 As Optional ByVal value2 As . . . . . . End Sub End Sub Optional keyword ExampleMethod() ExampleMethod() ExampleMethod(True) ExampleMethod(True) ExampleMethod(False, 10) ExampleMethod(False, 10) Optional parameter value2 _ _ Integer = 0) Integer = 0) Default value Invalid call Valid calls Optional Parameters PROGRAMMING FUNDAMENTALS Visual Basic 2005 76
    • Methods 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 Recursion PROGRAMMING FUNDAMENTALS Visual Basic 2005 77
    • Methods Recursive factorial program Module Recursion Module Recursion Sub Main() Sub Main() Dim factorialValue As Long Dim factorialValue As Long factorialValue = Factorial(5) factorialValue = Factorial(5) End Sub End Sub Function Factorial(ByVal number As Integer) As Long Function Factorial(ByVal number As Integer) As Long If number <= 1 Then ' base case If number <= 1 Then ' base case Return 1 Return 1 Else Else Return number * Factorial(number - 1) Return number * Factorial(number - 1) End If End If End Function End Function End Module End Module Recursion PROGRAMMING FUNDAMENTALS Visual Basic 2005 78
    • Methods Recursive program evaluation of the factorial Final value = 20 5! 5! 5! = 5 * 24 = 120 is returned 5 * 4! 5 * 4! 4! = 4 * 6 = 24 is returned 4 * 3! 4 * 3! 3! = 3 * 2 = 6 is returned 3 * 2! 3 * 2! 2! = 2 * 1 = 2 is returned 2 * 1! 2 * 1! 1 is returned 1 (a) Procession of recursive calls 1 (b) Values returned from each recursive call Recursion PROGRAMMING FUNDAMENTALS Visual Basic 2005 79
    • 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. Arrays Objectives PROGRAMMING FUNDAMENTALS Visual Basic 2005 80
    • Arrays 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 Arrays PROGRAMMING FUNDAMENTALS Visual Basic 2005 81
    • Arrays Array consisting of 12 elements Name of array (note that all elements of this array have the same name, numberArray) -45 numberArray(1) 6 numberArray(2) 0 numberArray(3) 72 numberArray(4) 1543 numberArray(5) -89 numberArray(6) 0 numberArray(7) 62 numberArray(8) Position number (index or subscript) of the element within array numberArray numberArray(0) -3 numberArray(9) 1 numberArray(10) 6453 numberArray(11) 78 Arrays PROGRAMMING FUNDAMENTALS Visual Basic 2005 82
    • Arrays Using arrays numberArray(5) = 100 numberArray(5) = 100 Assign 100 to sixth element of numberArray index1 = 3 index1 = 3 numberArray(index1 + 5) = 562 numberArray(index1 + 5) = 562 Assign 562 to ninth element of numberArray sum = numberArray(2) + numberArray(4) + numberArray(6) sum = numberArray(2) + numberArray(4) + numberArray(6) Get the sum of the 3rd, 5th, and 7th element of numberArray and assign to sum variable Arrays PROGRAMMING FUNDAMENTALS Visual Basic 2005 83
    • Arrays Arrays occupy space in memory The 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 Declaring and Allocating Arrays PROGRAMMING FUNDAMENTALS Visual Basic 2005 84
    • Arrays Declaring an array Dim numberArray As Integer() Dim numberArray As Integer() Or Or Dim numberArray() As Integer Dim numberArray() As Integer numberArray = New Integer(11){} numberArray = New Integer(11){} Or Or numberArray = New Integer(0 To 11){} numberArray = New Integer(0 To 11){} Allocate 12 elements in memory Dim numberArray As New Integer(11){} Dim numberArray As New Integer(11){} Or Or Dim numberArray As Integer() = New Integer(11){} Dim numberArray As Integer() = New Integer(11){} Declaring and Allocating Arrays PROGRAMMING FUNDAMENTALS Visual Basic 2005 85
    • Arrays Initializing an array Dim numberArray As Integer() Dim numberArray As Integer() numberArray = New Integer(11){1, 2, 3, 4} numberArray = New Integer(11){1, 2, 3, 4} Or Or Dim numberArray As Integer() = New Integer(11){1, 2, 3, 4} Dim numberArray As Integer() = New Integer(11){1, 2, 3, 4} Initial values Declaring and Allocating Arrays PROGRAMMING FUNDAMENTALS Visual Basic 2005 86
    • Arrays Sample program ‘ Declaring and allocating an array. ‘ Declaring and allocating an array. Module CreateArray Module CreateArray Sub Main() Sub Main() Dim array As Integer() ' declare array variable Dim array As Integer() ' declare array variable ‘ allocate memory for 10-element array using explicit ‘ allocate memory for 10-element array using explicit ‘ array ‘ array array = array = bounds bounds New Integer(0 To 9) {} New Integer(0 To 9) {} Console.WriteLine("Index " & vbTab & "Value") Console.WriteLine("Index " & vbTab & "Value") ' display values in array ' display values in array For i As Integer = 0 To array.GetUpperBound(0) For i As Integer = 0 To array.GetUpperBound(0) Console.WriteLine(i & vbTab & array(i)) Console.WriteLine(i & vbTab & array(i)) Next Next Console.WriteLine(vbCrLf & "The array contains " & _ Console.WriteLine(vbCrLf & "The array contains " & _ array.Length & " elements.") array.Length & " elements.") End Sub ' Main End Sub ' Main End Module ' CreateArray End Module ' CreateArray Declaring and Allocating Arrays PROGRAMMING FUNDAMENTALS Visual Basic 2005 87
    • Arrays To pass an array argument to a method, specify the name of the array without using parentheses Dim hourlyTemperatures As Integer() = New Integer(24){} Dim hourlyTemperatures As Integer() = New Integer(24){} . . . . . . DayData(hourlyTemperatures) DayData(hourlyTemperatures) . . . . . . Sub DayData(ByVal tempData As Integer()) Sub DayData(ByVal tempData As Integer()) . . . . . . End Sub End Sub Method header for DayData passes array hourlyTemperatures to method DayData hourlyTemperatures Integer array Passing an Array to a Method PROGRAMMING FUNDAMENTALS Visual Basic 2005 88
    • Arrays 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 . . . . . . Dim gradeArray As Integer() = New Integer() _ Dim gradeArray As Integer() = New Integer() _ {77, 68, 86, 73, 98, 87, 89, 81, 70, 90, 86, 81} {77, 68, 86, 73, 98, 87, 89, 81, 70, 90, 86, 81} Dim lowGrade As Integer = 100 Dim lowGrade As Integer = 100 ' use For Each...Next to find the minimum grade ' use For Each...Next to find the minimum grade For Each grade As Integer In gradeArray For Each grade As Integer In gradeArray If grade < lowGrade Then If grade < lowGrade Then lowGrade = grade lowGrade = grade End If End If Next Next . . . . . . For Each..Next Repetition Staement PROGRAMMING FUNDAMENTALS Visual Basic 2005 89
    • Arrays Often called multiple-subscripted arrays Multidimensional arrays require two or more indices to identify particular elements There are two types of multidimensional arrays: ◦ rectangular ◦ jagged Multidimensional Arrays PROGRAMMING FUNDAMENTALS Visual Basic 2005 90
    • Arrays Rectangular arrays with two indices often are used to represent tables of values consisting of information arranged in rows and columns Column 0 Column 1 Column 2 Column 3 Row 0 a(0, 0) a(0, 1) a(0, 2) a(0, 3) Row 1 a(1, 0) a(1, 1) a(1, 2) a(1, 3) Row 2 a(2, 0) a(2, 1) a(2, 2) a(2, 3) Column index Row index Array name Multidimensional Arrays PROGRAMMING FUNDAMENTALS Visual Basic 2005 91
    • Arrays Declaring arrays and initializing rectangular Dim numbers As Integer(,) = New Integer(1,1) {} Dim numbers As Integer(,) = New Integer(1,1) {} numbers(0, numbers(0, numbers(0, numbers(0, numbers(1, numbers(1, numbers(1, numbers(1, 0) 0) 1) 1) 0) 0) 1) 1) = = = = = = = = 1 1 2 2 3 3 4 4 ' ' ' ' ' ' ' ' leftmost element in row 0 leftmost element in row 0 rightmost element in row 0 rightmost element in row 0 leftmost element in row 1 leftmost element in row 1 rightmost element in row 1 rightmost element in row 1 Or Or Dim numbers As Integer(,) = New Integer(,) {{1,2}, {3,4}} Dim numbers As Integer(,) = New Integer(,) {{1,2}, {3,4}} Column 0 Column 1 Row 0 1 2 Row 1 3 4 Multidimensional Arrays PROGRAMMING FUNDAMENTALS Visual Basic 2005 92
    • Arrays Jagged arrays are maintained as arrays of arrays Unlike rectangular arrays, rows in jagged arrays can be of different lengths Col 0 Row 2 a(0)(0) a(0)(1) a(0)(2) Col 1 Col 2 Col 3 a(1)(0) a(1)(1) a(1)(2) a(1)(3) Col 0 Row 1 Col 2 Col 0 Row 0 Col 1 Col 1 a(2)(0) a(2)(1) Column index Row index Multidimensional Arrays Array name PROGRAMMING FUNDAMENTALS Visual Basic 2005 93
    • Arrays Declaring and initializing jagged arrays ' create jagged array ' create jagged array Dim array1 As Integer()() = New Integer(2)(){} ' three rows Dim array1 As Integer()() = New Integer(2)(){} ' three rows array1(0) array1(0) array1(1) array1(1) array1(2) array1(2) New New New New New New Integer() Integer() Integer() Integer() Integer() Integer() {1, {1, {3} {3} {4, {4, Col 0 Row 0 = = = = = = Col 1 1 2} 2} ' ' ' ' 5, 6} ' 5, 6} ' row row row row row row 0 0 1 1 2 2 is is is is is is a a a a a a single single single single single single array array array array array array 2 Col 0 Row 1 3 Col 0 Row 2 Col 1 Col 2 4 5 6 Multidimensional Arrays PROGRAMMING FUNDAMENTALS Visual Basic 2005 94
    • Arrays Sample Program ' Initializing a jagged array. ' Initializing a jagged array. Module JaggedArray Module JaggedArray Sub Main() Sub Main() ' create jagged array ' create jagged array Dim array1 As Integer()() Dim array1 As Integer()() array1(0) = New Integer() array1(0) = New Integer() array1(1) = New Integer() array1(1) = New Integer() array1(2) = New Integer() array1(2) = New Integer() = New Integer(2)(){}' three rows = New Integer(2)(){}' three rows {1, 2} ' row 0 is a single array {1, 2} ' row 0 is a single array {3} ' row 1 is a single array {3} ' row 1 is a single array {4, 5, 6} ' row 2 is a single array {4, 5, 6} ' row 2 is a single array Console.WriteLine("Values in jagged array1 by row are") Console.WriteLine("Values in jagged array1 by row are") ' output array1 elements ' output array1 elements For i As Integer = 0 To array1.GetUpperBound(0) For i As Integer = 0 To array1.GetUpperBound(0) For j As Integer = 0 To array1(i).GetUpperBound(0) For j As Integer = 0 To array1(i).GetUpperBound(0) Console.Write(array1(i)(j) & " ") Console.Write(array1(i)(j) & " ") Next Next Console.WriteLine() Console.WriteLine() Next Next End Sub ' Main End Sub ' Main End Module ' JaggedArray End Module ' JaggedArray Multidimensional Arrays PROGRAMMING FUNDAMENTALS Visual Basic 2005 95
    • Arrays It is possible to create methods that receive a variable number of arguments, using keyword ParamArray . . . . . . Sub Main Sub Main AnyNumberOfArguments() AnyNumberOfArguments() AnyNumberOfArguments(2, 3) AnyNumberOfArguments(2, 3) AnyNumberOfArguments(7, 8, 9, 10, 11, 12) AnyNumberOfArguments(7, 8, 9, 10, 11, 12) End Sub End Sub Sub AnyNumberOfArguments(ByVal ParamArray array1 As Sub AnyNumberOfArguments(ByVal ParamArray array1 As Integer()) Integer()) . . . . . . End Sub End Sub . . . . . . ParamArray keyword Variable-Length Parameter List PROGRAMMING FUNDAMENTALS Visual Basic 2005 96
    • Arrays 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 The ReDim Statement PROGRAMMING FUNDAMENTALS Visual Basic 2005 97
    • Arrays Using ReDim statements to change the array size . . . . Dim Dim Dim Dim . . array As Integer() = {1, 2, 3, 4, 5} array As Integer() = {1, 2, 3, 4, 5} arrayCopy As Integer() = array arrayCopy As Integer() = array . . . . . . ' change the size of the array without the Preserve keyword ' change the size of the array without the Preserve keyword ReDim array(6) ReDim array(6) . . . . . . ' change the size of the array with the Preserve keyword ' change the size of the array with the Preserve keyword ReDim Preserve arrayCopy(6) ReDim Preserve arrayCopy(6) arrayCopy(6) = 7 ' assign 7 to array element 6 arrayCopy(6) = 7 ' assign 7 to array element 6 Preserve keyword preserves the content of the array The ReDim Statement PROGRAMMING FUNDAMENTALS Visual Basic 2005 98
    • Arrays 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 Passing Arrays: ByVal vs ByRef PROGRAMMING FUNDAMENTALS Visual Basic 2005 99
    • Exercise PROGRAMMING FUNDAMENTALS 100
    • End of Programming Fundamentals PROGRAMMING FUNDAMENTALS 101