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

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

Embed Size (px)

Citation preview

Page 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

1

CS 106Computing Fundamentals II

Chapter 75“Arrays”

Herbert G. Mayer, PSU CSHerbert G. Mayer, PSU CSStatus 7/31/2013Status 7/31/2013

Initial content copied verbatim fromInitial content copied verbatim fromCS 106 material developed byCS 106 material developed by

CS professors: Cynthia Brown & Robert MartinCS professors: Cynthia Brown & Robert Martin

Page 2: 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

2

Syllabus What is An ArrayWhat is An Array

Arrays vs. RangesArrays vs. Ranges

VBA ArraysVBA Arrays

Dynamic ArraysDynamic Arrays

More DimensionsMore Dimensions

ArrayRangeDemoArrayRangeDemo

Copy Range to ArrayCopy Range to Array

Row vs. ColumnRow vs. Column

Using Random DataUsing Random Data

Page 3: 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

3

What is an Array?

• An array is a collection of objects of the same type, An array is a collection of objects of the same type, each called an array elementeach called an array element

• Each element is identified by a unique number, its Each element is identified by a unique number, its indexindex, while keeping the array name, while keeping the array name

• The index selects one element from the collective The index selects one element from the collective array data structurearray data structure

• In this way arrays resemble Excel rangesIn this way arrays resemble Excel ranges

• As with ranges, you can perform operations on an As with ranges, you can perform operations on an array in an efficient way using loopsarray in an efficient way using loops

3

Page 4: 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

4

Arrays vs. Ranges

• Array indexing is faster than range access, especially Array indexing is faster than range access, especially if dealing with large amounts of dataif dealing with large amounts of data

• Arrays offer more than three dimensionsArrays offer more than three dimensions

Page 5: 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

5

VBA Arrays

• VBA arrays are declared like variables:VBA arrays are declared like variables:

DimDim name name As String As String ‘creates 1 string‘creates 1 string

DimDim a(20) a(20) As String As String ‘array of 20 strings ‘array of 20 strings

• The second The second DimDim creates an array of 20 elements, each a creates an array of 20 elements, each a string, numbered from 1 to 20string, numbered from 1 to 20

• This numbering is called: This numbering is called: indexingindexing

• Plausible indexed references are Plausible indexed references are a(3)a(3) or or a(j+3*i)a(j+3*i)

• You can optionally set your module to start numbering You can optionally set your module to start numbering at 0 instead of 1; we’ll stick with default low index 1at 0 instead of 1; we’ll stick with default low index 1

5

Page 6: 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

6

Alternate Array Declarations

• Instead of using the simplest form of declaration, you Instead of using the simplest form of declaration, you can use the following in VBA: can use the following in VBA:

Dim testArray( 1 To 20 ) As DoubleDim 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 StringDim anotherTestArray(1955 To 2020) As String

Page 7: 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

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 = The compiler/interpreter selects the address = location in the computer’s memorylocation in the computer’s memory

• You reference the memory location by using the You reference the memory location by using the name of the variablename of the variable

• An array stores a sequence of values, conceptually in An array stores a sequence of values, conceptually in sequential ordersequential order

• You reference an element by using the array name You reference an element by using the array name andand an index an index

7

Page 8: 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

8

Arrays vs Variables

8

Variable num of type Double occupies some location in memorynum

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

Page 9: 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

9

Things to Watch

• Careful not to try to put more items in the array than it Careful not to try to put more items in the array than it will hold (bounds violation)will hold (bounds violation)

• Doing so causes a runtime errorDoing so causes a runtime error

• DonDon’’t index outside the allowable range of an array. t index outside the allowable range of an array. This should also cause a runtime errorThis should also cause a runtime error

9

Page 10: 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

10

Array Size to Use

• Declare your array big enough to handle any Declare your array big enough to handle any reasonable index rangereasonable index range

• In many languages you are out of luck if you guess In many languages you are out of luck if you guess wrong and run out of space in your arraywrong and run out of space in your array

• VBA offers an unusual VBA offers an unusual ReDimReDim feature feature

10

Page 11: 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

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 It lets you change the size of an array while the program is running!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 Without the PreservePreserve, data in original the array would , data in original the array would be lost when you ReDimbe lost when you ReDim

11

Page 12: 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

12

Dynamic Arrays

• You can also declare an array without giving it an You can also declare an array without giving it an initial size. This is called a initial size. This is called a dynamic arraydynamic array. Empty . Empty parens convey this to VBAparens convey this to VBA

Dim testDynamic() As String ‘ dynamic arrayDim testDynamic() As String ‘ dynamic array

• Later in the program, when you know how big you Later in the program, when you know how big you need it to be, you can use ReDim to set the size:need it to be, you can use ReDim to set the size:

ReDim testDynamic (1 to size)ReDim testDynamic (1 to size)

Page 13: 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

13

More Dimensions

• We’ve been looking at one-dimensional arrays, but an We’ve been looking at one-dimensional arrays, but an array can have more dimensionsarray can have more dimensions

• In some languages, a multi-dimensional array type is In some languages, a multi-dimensional array type is literally an array of arrays, but VBA uses multiple literally an array of arrays, but VBA uses multiple dimensions to the same effectdimensions to the same effect

• Example:Example:

Dim arrayName ( 1 To 3, 1 To 4 ) As IntegerDim arrayName ( 1 To 3, 1 To 4 ) As Integer

‘ ‘ how many elements total?how many elements total?

13

Page 14: 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

14

The Whole Array

Dim arrayName( 1 To 3, 1 To 4 ) As IntegerDim arrayName( 1 To 3, 1 To 4 ) As Integer

arrayName( 1, 2 ) = 20arrayName( 1, 2 ) = 20 ‘row 1, column 2‘row 1, column 2

14

201

2

3

1 2 3 4

Page 15: 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

15

Copying A Range to an Array

• Handy if you are going to do extensive Handy if you are going to do extensive computations on the values in the rangecomputations on the values in the range

• It is possible to do this directly with one It is possible to do this directly with one statement, if everything is declared just right statement, if everything is declared just right (for info see (for info see msdn.microsoft.com/en-us/library)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

Page 16: 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

16

Declarations

Here is our array declaration:Here is our array declaration:

Const DIM1 As Integer = 8 ’ lengthConst DIM1 As Integer = 8 ’ length

Const DIM2 As Integer = 10 ’ widthConst DIM2 As Integer = 10 ’ width

Dim demo2DArray( 1 To DIM1, 1 To DIM2 ) As DoubleDim demo2DArray( 1 To DIM1, 1 To DIM2 ) As Double

And the range:And the range:

Dim twoDArea As Range ’ globalDim twoDArea As Range ’ global

Sub Workbook_Open()Sub Workbook_Open()

Set twoDArea = Range(Cells(1, 1), Cells(DIM1, DIM2))Set twoDArea = Range(Cells(1, 1), Cells(DIM1, DIM2))

End SubEnd Sub

Page 17: 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

17

Copy Range to Array

SubSub RangetoTwoDArray() RangetoTwoDArray()

Dim Dim rowNdx rowNdx As IntegerAs Integer, colNdx , colNdx As IntegerAs Integer

ForFor rowNdx = 1 rowNdx = 1 ToTo DIM1 DIM1

ForFor colNdx = 1 colNdx = 1 ToTo DIM2 DIM2

demo2DArray(rowNdx, colNdx) = demo2DArray(rowNdx, colNdx) = Cells(rowNdx, colNdx).ValueCells(rowNdx, colNdx).Value

NextNext colNdx colNdx

NextNext rowNdx rowNdx

End SubEnd Sub

Page 18: 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

18

Row vs. Column

• For some reason, in a two-dimensional array or For some reason, in a two-dimensional array or range, it is customary to have the outer loop go row range, it is customary to have the outer loop go row by row and the inner loop go across the columnsby row and the inner loop go across the columns

• The next few slides show you this method and also The next few slides show you this method and also how to go column by column insteadhow to go column by column instead

Page 19: 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

19

Filling the Range by Rows

SubSub FillRangeByRow() FillRangeByRow() DimDim rowNdx rowNdx As IntegerAs Integer

Dim colNdx Dim colNdx As IntegerAs IntegerDim count Dim count As IntegerAs Integercount = 1count = 1ForFor rowNdx = 1 rowNdx = 1 ToTo DIM1 DIM1

ForFor colNdx = 1 colNdx = 1 ToTo DIM2 DIM2Cells( rowNdx, colNdx ) = countCells( rowNdx, colNdx ) = countcount = count + 1count = count + 1

NextNext colNdx colNdxNextNext rowNdx rowNdx

End SubEnd Sub

Page 20: 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

20

The Result

Note how the numbers increase across the rows first.

Page 21: 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

21

Filling the Range by Columns

SubSub FillRangeByColumn() FillRangeByColumn()

Dim Dim rowNdx rowNdx As IntegerAs Integer, colNdx , colNdx As IntegerAs Integer, count As , count As IntegerInteger

count = 1count = 1

ForFor colNdx = 1 colNdx = 1 ToTo DIM2 DIM2

ForFor rowNdx = 1 rowNdx = 1 ToTo DIM1 DIM1

Cells(rowNdx, colNdx) = countCells(rowNdx, colNdx) = count

count = count + 1count = count + 1

Next Next rowNdxrowNdx

NextNext colNdx colNdx

End SubEnd Sub

Page 22: 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

22

The Result

Note how the numbers increase down the columns first

Page 23: 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

23

Using Random Data

• The demo has examples of filling the range (or array) The demo has examples of filling the range (or array) with random data, either the basic random numbers with random data, either the basic random numbers which range between 0 and 1, or a modified version which range between 0 and 1, or a modified version that generates random numbers between 1 and 6that generates random numbers between 1 and 6

• It also includes code for doing some data It also includes code for doing some data manipulation while the data is in the array; give it a manipulation while the data is in the array; give it a try!try!