Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 CS 106 Computing Fundamentals II Chapter 75 “Arrays” Herbert G. Mayer, PSU CS Status 7/31/2013 Initial content copied verbatim from CS 106 material developed.

Similar presentations


Presentation on theme: "1 CS 106 Computing Fundamentals II Chapter 75 “Arrays” Herbert G. Mayer, PSU CS Status 7/31/2013 Initial content copied verbatim from CS 106 material developed."— Presentation transcript:

1 1 CS 106 Computing Fundamentals II Chapter 75 “Arrays” Herbert G. Mayer, PSU CS Status 7/31/2013 Initial content copied verbatim from CS 106 material developed by CS professors: Cynthia Brown & Robert Martin

2 2 Syllabus What is An Array What is An Array Arrays vs. Ranges Arrays vs. Ranges VBA Arrays VBA Arrays Dynamic Arrays Dynamic Arrays More Dimensions More Dimensions ArrayRangeDemo ArrayRangeDemo Copy Range to Array Copy Range to Array Row vs. Column Row vs. Column Using Random Data Using Random Data

3 3 What is an Array? An array is a collection of objects of the same type, each called an array elementAn array is a collection of objects of the same type, each called an array element Each element is identified by a unique number, its index, while keeping the array nameEach element is identified by a unique number, its index, while keeping the array name The index selects one element from the collective array data structureThe index selects one element from the collective array data structure In this way arrays resemble Excel rangesIn this way arrays resemble Excel ranges As with ranges, you can perform operations on an array in an efficient way using loopsAs with ranges, you can perform operations on an array in an efficient way using loops 3

4 4 Arrays vs. Ranges Array indexing is faster than range access, especially if dealing with large amounts of dataArray indexing is faster than range access, especially if dealing with large amounts of data Arrays offer more than three dimensionsArrays offer more than three dimensions

5 5 VBA Arrays VBA arrays are declared like variables:VBA arrays are declared like variables: Dim name As String ‘creates 1 string Dim a(20) As String ‘array of 20 strings The second Dim creates an array of 20 elements, each a string, numbered from 1 to 20The second Dim creates an array of 20 elements, each a string, numbered from 1 to 20 This numbering is called: indexingThis numbering is called: indexing Plausible indexed references are a(3) or a(j+3*i)Plausible indexed references are a(3) or a(j+3*i) You can optionally set your module to start numbering at 0 instead of 1; we’ll stick with default low index 1You can optionally set your module to start numbering at 0 instead of 1; we’ll stick with default low index 1 5

6 6 Alternate Array Declarations Instead of using the simplest form of declaration, you can use the following in VBA:Instead of using the simplest form of declaration, you can use the following in VBA: Dim testArray( 1 To 20 ) As Double Or even use a different lower bound:Or even use a different lower bound: Dim anotherTestArray(1955 To 2020) As String

7 7 Arrays vs. Scalar Variables A variable is a named place to store a valueA variable is a named place to store a value The compiler/interpreter selects the address = location in the computer’s memoryThe compiler/interpreter selects the address = location in the computer’s memory You reference the memory location by using the name of the variableYou reference the memory location by using the name of the variable An array stores a sequence of values, conceptually in sequential orderAn array stores a sequence of values, conceptually in sequential order You reference an element by using the array name and an indexYou reference an element by using the array name and an index 7

8 8 Arrays vs Variables 8 Variable num of type Double occupies some location in memory num 3.2 Array numArray() of type Double has 6 elements and occupies 6 times the memory of one variable of type Double. Here, numArray(3) has value 3.5. numArray 1.3 2.4 3.5 4.6 5.7 6.8 1 2 3 4 5 6

9 9 Things to Watch Careful not to try to put more items in the array than it will hold (bounds violation)Careful not to try to put more items in the array than it will hold (bounds violation) Doing so causes a runtime errorDoing so causes a runtime error Don’t index outside the allowable range of an array. This should also cause a runtime errorDon’t index outside the allowable range of an array. This should also cause a runtime error 9

10 10 Array Size to Use Declare your array big enough to handle any reasonable index rangeDeclare your array big enough to handle any reasonable index range In many languages you are out of luck if you guess wrong and run out of space in your arrayIn many languages you are out of luck if you guess wrong and run out of space in your array VBA offers an unusual ReDim featureVBA offers an unusual ReDim feature 10

11 11 ReDim This is a handy and quite unusual feature of VBThis is a handy and quite unusual feature of VB It lets you change the size of an array while the program is running!It lets you change the size of an array while the program is running! Example:Example: Dim exampleArray( small_Size )... ‘ now small_Size ends up being to small, then: ReDim Preserve exampleArray( 1 To big_Size ) ‘ big_Size being an integer value greater than small_Size Without the Preserve, data in original the array would be lost when you ReDimWithout the Preserve, data in original the array would be lost when you ReDim 11

12 12 Dynamic Arrays You can also declare an array without giving it an initial size. This is called a dynamic array. Empty parens convey this to VBAYou can also declare an array without giving it an initial size. This is called a dynamic array. Empty parens convey this to VBA Dim testDynamic() As String ‘ dynamic array Later in the program, when you know how big you need it to be, you can use ReDim to set the size:Later in the program, when you know how big you need it to be, you can use ReDim to set the size: ReDim testDynamic (1 to size)

13 13 More Dimensions We’ve been looking at one-dimensional arrays, but an array can have more dimensionsWe’ve been looking at one-dimensional arrays, but an array can have more dimensions In some languages, a multi-dimensional array type is literally an array of arrays, but VBA uses multiple dimensions to the same effectIn some languages, a multi-dimensional array type is literally an array of arrays, but VBA uses multiple dimensions to the same effect Example:Example: Dim arrayName ( 1 To 3, 1 To 4 ) As Integer ‘ how many elements total? 13

14 14 The Whole Array Dim arrayName( 1 To 3, 1 To 4 ) As Integer arrayName( 1, 2 ) = 20‘row 1, column 2 14 20 1 2 3 1 234

15 15 Copying A Range to an Array Handy if you are going to do extensive computations on the values in the rangeHandy if you are going to do extensive computations on the values in the range It is possible to do this directly with one statement, if everything is declared just right (for info see msdn.microsoft.com/en- us/library)It is possible to do this directly with one statement, if everything is declared just right (for info see msdn.microsoft.com/en- us/library) We’ll do it cell by cell using a nested loopWe’ll do it cell by cell using a nested loop

16 16 Declarations Here is our array declaration: Const DIM1 As Integer = 8 ’ length Const DIM2 As Integer = 10 ’ width Dim demo2DArray( 1 To DIM1, 1 To DIM2 ) As Double And the range: Dim twoDArea As Range ’ global Sub Workbook_Open() Set twoDArea = Range(Cells(1, 1), Cells(DIM1, DIM2)) Set twoDArea = Range(Cells(1, 1), Cells(DIM1, DIM2)) End Sub

17 17 Copy Range to Array Sub RangetoTwoDArray() Dim rowNdx As Integer, colNdx As Integer Dim rowNdx As Integer, colNdx As Integer For rowNdx = 1 To DIM1 For rowNdx = 1 To DIM1 For colNdx = 1 To DIM2 For colNdx = 1 To DIM2 demo2DArray(rowNdx, colNdx) = Cells(rowNdx, colNdx).Value demo2DArray(rowNdx, colNdx) = Cells(rowNdx, colNdx).Value Next colNdx Next colNdx Next rowNdx Next rowNdx End Sub

18 18 Row vs. Column For some reason, in a two-dimensional array or range, it is customary to have the outer loop go row by row and the inner loop go across the columnsFor some reason, in a two-dimensional array or range, it is customary to have the outer loop go row by row and the inner loop go across the columns The next few slides show you this method and also how to go column by column insteadThe next few slides show you this method and also how to go column by column instead

19 19 Filling the Range by Rows Sub FillRangeByRow() Dim rowNdx As Integer Dim rowNdx As Integer Dim colNdx As Integer Dim count As Integer count = 1 For rowNdx = 1 To DIM1 For colNdx = 1 To DIM2 Cells( rowNdx, colNdx ) = count count = count + 1 Next colNdx Next rowNdx End Sub

20 20 The Result Note how the numbers increase across the rows first.

21 21 Filling the Range by Columns Sub FillRangeByColumn() Dim rowNdx As Integer, colNdx As Integer, count As Integer Dim rowNdx As Integer, colNdx As Integer, count As Integer count = 1 count = 1 For colNdx = 1 To DIM2 For colNdx = 1 To DIM2 For rowNdx = 1 To DIM1 For rowNdx = 1 To DIM1 Cells(rowNdx, colNdx) = count Cells(rowNdx, colNdx) = count count = count + 1 count = count + 1 Next rowNdx Next rowNdx Next colNdx Next colNdx End Sub

22 22 The Result Note how the numbers increase down the columns first

23 23 Using Random Data The demo has examples of filling the range (or array) with random data, either the basic random numbers which range between 0 and 1, or a modified version that generates random numbers between 1 and 6The demo has examples of filling the range (or array) with random data, either the basic random numbers which range between 0 and 1, or a modified version that generates random numbers between 1 and 6 It also includes code for doing some data manipulation while the data is in the array; give it a try!It also includes code for doing some data manipulation while the data is in the array; give it a try!


Download ppt "1 CS 106 Computing Fundamentals II Chapter 75 “Arrays” Herbert G. Mayer, PSU CS Status 7/31/2013 Initial content copied verbatim from CS 106 material developed."

Similar presentations


Ads by Google