CSCI 3131 01 Chapter 8 Arrays Instructor Bindra
CSCI 3131. 01 Chapter 8 Arrays Instructor: Bindra Shrestha University of Houston – Clear Lake
Acknowledgement Dr. Xinhua Chen And Starting Out with Visual Basic 2010 by Tony Gaddis and Kip Irvine
Chapter 8 Arrays, Timers, and More Topics • Declare and initialize a one-dimensional array • Search a one-dimensional array • Compute the sum and average of a one-dimensional array • Sort a one-dimensional array • Copy between arrays • Using For Each … Next with array • Create and manipulate parallel one-dimensional arrays • Create and initialize a two-dimensional array • Enabled property • Timer • Random number generation
Introduction • Arrays are like groups of variables that allow you to store sets of similar data – A single dimension array is useful for storing and working with a single set of data, like a column or a row of data. – A multidimensional array can be used to store and work with multiple sets of data. A two-dimensional array deals with data in a table. • Array programming techniques covered – Summing and averaging all the elements in an array – Summing all the columns in a two-dimensional array – Searching an array for a specific value – Using parallel arrays
Array Characteristics • An array stores multiple values of same type • Like a group of variables with a single name • For example, the days of the week might be: – a set of 7 string variables – with a maximum length of 9 characters • All variables within an array are called elements and must be of the same data type • You access the elements in an array through a subscript
Subscript Characteristics • A subscript, also called an index, is a number that identifies a specific element within an array • Subscript numbering works like a list box index: – Subscript numbering begins at 0 – 1 st element in an array is always subscript 0 – Last element is total number of elements – 1 • An array with 7 elements refers to the 1 st element as subscript 0 and the last element as subscript 6
Declaring a One-Dimensional Array Dim Array. Name(Upper. Subscript) As Data. Type • Array. Name is the variable name of the array • Upper. Subscript is the value of the array's highest subscript – Must be a positive whole number • Data. Type may be any Visual Basic data type • VB knows an array is declared when name is followed by parentheses with number of elements
Array Declaration Example Dim int. Hours(5) As Integer int. Hours(0) int. Hours(1) int. Hours(2) int. Hours(3) int. Hours(4) int. Hours(5) • Note that 6 elements are available when an array with an upper subscript of 5 is declared • Each element is an integer type
Default Initialization • All elements of an Integer array are initialized to zero – Same initialization as an integer variable • Each array element is initialized exactly the same as a simple variable of that data type – A Single is initialized to zero (0. 0) – A String is initialized to Nothing
Implicit Array Sizing & Initialization • An array can be initialized when declared • Example: Dim int. Numbers() As Integer = {2, 4, 5, 7, 9, 12} • This array is implicitly sized – – Upper subscript value is left blank Number of elements implied from initialization Upper subscript of 5 implied by this example This results in a 6 element array • Elements are assigned the values shown
Named Constant as Upper Subscript • A named constant may be used as an array's highest subscript instead of a number Const UPPER_SUB As Integer = 100 Dim array(UPPER_SUB) As Integer • This is a common use for named constants – Highest subscript is often used multiple times – If highest subscript changes, use of a named constant allows it to be changed in one place
Working With Array Elements • Simply include the subscript to use an array element like an ordinary variable • int. Numbers(2) refers to 3 rd element of array int. Numbers(0) int. Numbers(1) int. Numbers(2) int. Numbers(3) int. Numbers(4) int. Numbers(5) = = = 100 200 300 400 500 600 dec. Pay = int. Hours(3) * dec. Rate int. Numbers(0) += 1 Message. Box. Show(dec. Pay(5). To. String())
Arrays and Loops • Loops are frequently used to process arrays • Use a loop to prompt for 10 values Dim int. Nbrs(9) as Integers Dim int. Count As Integer For int. Count = 0 To 9 int. Nbrs(int. Count) = CInt(Input. Box("Enter number")) Next int. Count • Use a loop to reset values in the str. Names array to an empty string Dim str. Names(999) as String Dim int. Count As Integer For int. Count = 0 To 999 str. Names(int. Count) = "" Next int. Count
Array Bounds Checking • Visual Basic checks each subscript value of each array reference used at run time • A subscript is invalid if it is – Negative – Greater than the Upper. Subscript declared • An invalid subscript causes VB to throw a run-time exception • Bounds checking is not done at design time
For Each Loop Array Processing • A For…Each loop is similar to a For…Next • Iterates for each element in the array • str. Name is assigned the value of the next array element at each iteration Dim str. Employees() As String = {"Jim", "Sally", _ "Henry", "Jean", "Renee"} Dim str. Name As String For Each str. Name In str. Employees Message. Box. Show(str. Name) Next str. Name • Tutorial 8 -1 demonstrates array processing
Use For Each To Sum an Array Private int. Array() as Integer = {10, 20, 90, -20) Dim int. Sum as Integer = 0 For Each int. Val as Integer in int. Array int. Sum = int. Sum + int. Val Next • Start of iteration 1 int. Val = 10 • End of iteration 1 int. Val = 10 int. Sum = 10 • Start of iteration 2 int. Val = 20 • End of iteration 2 int. Val = 20 int. Sum = 10 int. Sum = 30 • Start of iteration 3 int. Val = 90 • End of iteration 3 int. Val = 90 int. Sum = 30 int. Sum = 120 • End of iteration 4 int. Val = -20 • Start of iteration 4 int. Val = -20 int. Sum = 100
Use For Each To Find Largest Value Dim int. Array() as Integer = {10, 20, 90, -20) Dim int. Largest as Integer = int. Array(0) For Each int. Val as Integer in int. Array If int. Val > int. Largest Then int. Largest = int. Val Next • Start of iteration 1 int. Val = 10 • End of iteration 1 int. Val = 10 int. Largest = 10 • Start of iteration 2 int. Val = 20 • End of iteration 2 int. Val = 20 int. Largest = 10 int. Largest = 20 • Start of iteration 3 int. Val = 90 • End of iteration 3 int. Val = 90 int. Largest = 30 int. Largest = 90 • End of iteration 4 int. Val = -20 • Start of iteration 4 int. Val = -20 int. Largest = 90
Determining Number of Elements • Arrays have a Length property that holds the number of elements in the array Dim int. Values(25) As Integer For int. Count = 0 to (int. Values. Length – 1) Message. Box. Show(int. Values(int. Count). To. String) Next int. Count • Note that length is number of array elements, not the upper subscript of the array • Length property always 1 greater than the upper subscript
Total the Values in an Array • Variable to hold sum (int. Total)is initialized to zero prior to loop • Iterate over all elements, adding each element to int. Total Dim int. Units(24) as Integer 'Declare array Dim int. Total As Integer = 0 'Initialize accumulator Dim int. Count as Integer 'Declare loop counter 'Find total of all values held in array For int. Count = 0 To (int. Units. Length – 1) int. Total += int. Units(int. Count) Next int. Count
Average the Values in an Array • Similar to previous example but then divides total by number of elements to get average Dim Dim int. Units(24) as Integer int. Total As Integer = 0 dbl. Average as Double int. Count as Integer 'Declare array 'Initialize accumulator 'Declare average var 'Declare loop counter 'Find total of all values held in array For int. Count = 0 To (int. Units. Length – 1) int. Total += int. Units(int. Count) Next int. Count 'Use floating-point division to compute average dbl. Average = int. Total / int. Units. Length
Find Highest & Lowest Array Values • Pick first element as the highest • Search rest of array for higher values • If a higher value is located, save the value Dim int. Numbers(24) as Integer Dim int. Count as Integer Dim int. Highest as Integer = int. Numbers(0) For int. Count = 1 To (int. Numbers. Length - 1) If int. Numbers(int. Count) > int. Highest Then int. Highest = int. Numbers(int. Count) End If Next int. Count • Use similar logic to find lowest value
Array Copy Using Loop • Copy one element at a time For int. Count = 0 To int. Old. Values. Length -1 int. New. Values(int. Count) = int. Old. Values(int. Count) Next int. Count • Note that array copy cannot be done by a simple assignment int. New. Values = int. Old. Values – Causes int. New. Values array to reference the same memory location as int. Old. Values – Thus any change to int. Old. Values will affect int. New. Values and vice versa – This is because arrays are object variables
Array Copy Using Copy Method of Array Syntax: Array. Copy(Source. Array, Dest. Array, length) Dim a() As Integer = {1, 2, 3, 4, 5, 6, 7, 8} Dim b() As Integer = {2, 3, 4, 5} Array. Copy(b, a, 4) '4 is the number of elements in b ' This makes array a contain: ' { 2, 3, 4, 5, 5, 6, 7, 8}
Parallel Arrays • Sometimes it’s useful to store related data in two or more arrays called parallel arrays – Causes the nth element of one array to be related to the nth element of another • Allows related data to be accessed using the same subscript on both arrays
Parallel Arrays Example • Assume the following array declarations Dim str. Names(4) As String Dim str. Addresses(4) As String • Element 1 refers to the same person with name in one array and address in the other str. Names(0) str. Names(1) str. Names(2) str. Names(3) str. Names(4) Person #1 Person #2 Person #3 Person #4 Person #5 str. Addresses(0) str. Addresses(1) str. Addresses(2) str. Addresses(3) str. Addresses(4)
Parallel Arrays Processing • Use parallel array processing to add name and address of each person to a list box Dim str. Names(4) As String Dim str. Addresses(4) As String For int. Count = 0 To 4 lst. People. Items. Add("Name: " & str. Names(int. Count) _ & " Address: " & str. Addresses(int. Count)) Next int. Count • Tutorial 8 -2 has an example of parallel arrays
Array & List Box Parallel Processing • A list box selection used as an array index ' Initialize a List Box with names lst. People. Items. Add("Jean James") ' Subscript 0 lst. People. Items. Add("Kevin Smith") ' Subscript 1 lst. People. Items. Add("Joe Harrison") ' Subscript 2 ' Initialize an Array with corresponding phone numbers phone. Numbers(0) = "555 -2987" phone. Numbers(1) = "555 -5656" phone. Numbers(2) = "555 -8897" ' Process a selection If lst. People. Selected. Index > -1 And _ lst. People. Selected. Index < phone. Numbers. Length Then Message. Box. Show(phone. Numbers(lst. People. Selected. Index)) Else Message. Box. Show("That is not a valid selection. ") End If
Searching Arrays, The Search • Find 1 st instance of value 100 in array int. Scores • int. Position gives position of this value Dim bln. Found as Boolean = False Dim int. Count as Integer = 0 Dim int. Position as Integer = -1 ' Search for a 100 in the array Do While Not bln. Found And int. Count < scores. Length If int. Scores(int. Count) = 100 Then bln. Found = True int. Position = int. Count End If int. Count += 1 Loop
Searching Arrays, The Result • Indicates whether the value was found • If found, position is given as a test number ' Was 100 found in the array? If bln. Found Then Message. Box. Show( _ "Congratulations! You made a 100 on test " & _ (int. Position + 1). To. String, "Test Results") Else Message. Box. Show( _ "You didn’t score a 100, but keep trying!", _ "Test Results") End If
Sorting an Array, Ascending • Arrays have a Sort method • Arranges elements in ascending order (lowest to highest) • Sort int. Numbers in this order: {1, 3, 6, 7, 12} Dim int. Numbers() As Integer = { 7, 12, 1, 6, 3 } Array. Sort(int. Numbers) • Sort str. Names in this order: {Alan, Bill, Kim, Sue} Dim str. Names() As String = { "Sue", "Kim", _ "Alan", "Bill" } Array. Sort(str. Names)
Sorting an Array, Descending • Use the Sort method in conjunction with the Reverse method • Arranges elements in descending order (highest to lowest) • Sort int. Numbers in this order: {12, 7, 6, 3, 1} Dim int. Numbers() As Integer = { 7, 12, 1, 6, 3 } Array. Sort(int. Numbers) Array. Reverse() • Sort str. Names in this order: {Sue, Kim, Bill, Alan} Dim str. Names() As String = { "Sue", "Kim", _ "Alan", "Bill" } Array. Sort(str. Names) Array. Reverse()
Dynamically Sizing an Array Re. Dim [Preserve] Arrayname(Upper. Subscript) • Re. Dim is a new keyword – Used to change the number of elements at run time • If Preserve is specified, the existing contents of the array are preserved • Arraynames the existing array • Upper. Subscript specifies the new highest subscript value • Can declare an array with no subscript and state number of elements later with Re. Dim
Resizing Example • Array sng. Scores declared with no elements • User prompted for number of elements • Re. Dim resizes array based on user input Dim sng. Scores() As Single ' Declared with no elements Dim int. Num. Scores as Integer ' Obtain number of elements from the user int. Num. Scores = CInt(Input. Box("Enter number of test scores")) If int. Num. Scores > 0 Then Re. Dim sng. Scores(int. Num. Scores - 1) Else Message. Box. Show("You must enter 1 or greater. ") End If
Passing Arrays as Arguments to Procedures • Array int. Numbers passed to Display. Sum sub Dim int. Numbers() As Integer = { 2, 4, 7, 9, 8, 12 } Display. Sum(int. Numbers) • Sub computes & shows sum of array elements • Can pass any integer array to Display. Sum Sub Display. Sum(By. Val int. Array() As Integer) Dim int. Total As Integer = 0 ' Accumulator Dim int. Count As Integer ' Loop counter For int. Count = 0 To (int. Array. Length - 1) int. Total += int. Array(int. Count) Next Message. Box. Show("Total is " & int. Total. To. String) End Sub
Passing Arrays: By. Val and By. Ref • When passing an array By. Val – Calling procedure “sees” sub procedure changes to element values • Simple variables don’t work this way – If sub assigns array argument to another array, no effect on array in calling procedure • When passing an array By. Ref – Calling procedure “sees” sub procedure changes to element values – If sub assigns array argument to another array, calling procedure array values affected
Passing Arrays Example • After Reset. Values procedure executes, int. Numbers array still contains { 1, 2, 3, 4, 5 } • If array passed By. Ref, int. Numbers array will contain { 0, 0, 0 } after procedure runs Dim int. Numbers() As Integer = { 1, 2, 3, 4, 5 } Reset. Values(int. Numbers) Sub Reset. Values(By. Val int. Array() As Integer) Dim new. Array() As Integer = {0, 0, 0} int. Array = new. Array End Sub
An Array Returned From a Function • Return type String() indicates array of strings returned • Thus the function result must be assigned to an array of strings Function Get. Names() As String() ' Get four names from user ' Return them as an array of strings. Dim str. Names(3) As String Dim str. Input As String Dim int. Count As Integer For int. Count = 0 To 3 str. Input = Input. Box("Enter name " & _ (int. Count + 1). To. String) str. Names(int. Count) = str. Input Next Return str. Names End Function
A Two Dimensional Array Picture • Thus far, arrays have been one-dimensional • Arrays can also be two-dimensional • A two-dimensional array looks like a spreadsheet with rows and columns Column 0 Row 1 Row 2 Column 1 Column 2 Column 3
Two Dimensional Array Syntax Dim Array. Name(Upper. Row, Upper. Column) As Data. Type • Upper. Row and Upper. Column give the highest subscript for the row and column indices of the array • The array on the previous slide could be: Dim array(2, 3) As Single – Defines three rows; 0, 1, and 2 – And four columns; 0, 1, 2, and 3
Two Dimensional Array Subscripts Dim array(2, 3) As Single Column 0 Column 1 Column 2 Column 3 Row 0 sng. Scores(0, 0) sng. Scores(0, 1) sng. Scores(0, 2) sng. Scores(0, 3) Row 1 sng. Scores(1, 0) sng. Scores(1, 1) sng. Scores(1, 2) sng. Scores(1, 3) Row 2 sng. Scores(2, 0) sng. Scores(2, 1) sng. Scores(2, 2) sng. Scores(2, 3)
Nested Loops And Two Dimensions • Must use two subscripts to indicate a single element in a two dimensional array • Nested loops are often used to specify subscripts for two-dimensional array processing • For example, a nested loop below is used to insert a value into every element of array scores For int. Row = 0 To 2 For int. Col = 0 To 3 int. Num = Val(Input. Box("Enter a score. ")) sng. Scores(int. Row, int. Col) = int. Num Next int. Col Next int. Row
Implicit Sizing and Initialization • Can be used with multi-dimensional arrays: Dim int. Numbers(, ) As Integer = _ { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} } • Row 0 values • Row 1 values • Row 2 values • Initializes array int. Numbers with the following values Col 0 Col 1 Col 2 Row 0 1 2 3 Row 1 4 5 6 Row 2 7 8 9
Sum Columns, 2 -Dimensional Array • Code below uses nested loops to compute sum of elements in each column of a 2 dimensional array • Outer loop controls column subscript Dim int. Values(, ) As Integer = {{1, 2, 3, 4}, _ {5, 6, 7, 8}, _ {9, 10, 11, 12}} For int. Col = 0 to 3 int. Total = 0 'Initialize accumulator For int. Row = 0 to 2 'Sum rows in this column int. Total += int. Values(int. Row, int. Col) next int. Row 'Display the sum of the column Message. Box. Show("Column " & int. Col. To. String() _ & " sum is " & int. Total. To. String) Next int. Col
Three-Dimensional Arrays & Beyond • VB allows arrays of up to 32 dimensions • Can think of a 3 dimensional array as having multiple pages of two dimensional arrays • Arrays beyond three dimensions are difficult to visualize • But, all one needs to do is to be consistent in the use of the different indices
Enabled Property • Most controls have an Enabled property • If this Boolean property is set to false, the control is disabled, meaning the control: – Cannot receive the focus – Cannot respond to user generated events – Will appear dimmed, or grayed out • Default value for this property is true • May be set in code when needed as shown: btn. Example. Enabled = False
Timer Control • A Timer control generates Tick events – Double-click on Timer tool in Toolbox to add – Appears in component tray – Standard prefix is tmr • Can perform a process at regular intervals by coding the process in a Tick event procedure • Two important properties – Enabled must be true to generate Tick events – Interval (milliseconds) decides tick frequency • Interval of 1000 causes 1 timer tick per second • Tutorial 8 -5 demonstrates the Timer control
Splash Screens • A form, often with an application logo, that is displayed while an application is loading • A splash screen usually: – Has Topmost property set to True so it is displayed over the forms of other applications – Disappears shortly by using a Timer – Is modeless so the application continues to load while the splash screen is displayed • Tutorial 8 -6 demonstrates a splash screen
Anchor Property • Anchor - a property of various form controls • A control anchored to a form edge keeps the same distance to the form edge • Controls may be anchored to any, all, or none of the right, left, top, or bottom edges – Default is to anchor to top and left edges – Can just as easily anchor to bottom right – If anchoring to opposing sides, control is resized when form is resized – Anchoring to all 4 sides causes control to be resized proportionally to form
Dock Property • Dock - a property of various form controls • A control docked to a form edge is placed directly against the form edge • Controls may be docked to – Any one form edge but not more than one – No edge or not docked (the default) • Length or width of docked control changes to match length or width of the form edge
Initial Random Number Generation • Often used for games and simulations • Must create an instance of the Random class to use random number methods and properties Private rand as New Random • May supply a seed number as below so the same set of random numbers are generated every time Private rand as New Random(25) • If no seed number is supplied when instantiated: – VB uses its default random number seed – Causes each sequence to be unique
Generating More Random Numbers • The Next method returns the next integer in a random number sequence Dim int. Num as Integer = rand. Next() – Returns integer between 0 and 2, 147, 483, 647 • Repeatedly use a statement such as the following to generate additional random numbers int. Num = rand. Next()
Random Numbers in a Range • Can set an upper limit for the number generated by specifying the limit as an argument – Following example generates a random number between 0 and 99 int. Num = rand. Next(100) • Lower limit of a random number is always 0 – Can add or subtract to change this lower limit – Following example generates a random number between 50 and +49 int. Num = rand. Next(100) - 50
Random Numbers of Type Double • Use Next. Double method to generate random numbers of type double – Returns floating point number from 0. 0 to 1. 0 Dim dbl. Num as Double = rand. Next. Double() • For a random double between 0. 0 and 500. 0 dbl. Num = rand. Next. Double() * 500 • For a random double between 100. 0 and 600. 0 dbl. Num = (rand. Next. Double() * 500) + 100 • Tutorial 8 -7 shows an interesting use of random numbers
- Slides: 53