7
www.monash.edu.au IMS1906 Programming in VB.NET Week 7 – Lecture 1 & 2 Arrays Part 1 and II © Angela Carbone Monash University School of Information Management and Systems www.monash.edu.au 2 Lecture Outline Introduction to Arrays Defining Arrays (VB.NET) Declaring and Initialising Array Assigning values to Arrays Properties and methods of Array Class www.monash.edu.au 3 Motivation for arrays Much computer processing applies to sets of data Sets can be quite large Example: Calculate average rainfall Write a program which reads in the amount of rainfall for each of 6 months, displays the average rainfall followed by the individual monthly rainfall amounts. www.monash.edu.au 4 Rainfall Solution – Attempt 1 Read rainfall1 Read rainfall2 Read rainfall6 Average (rainfall1 + rainfall2 + rainfall3 + rainfall4 + rainfall5 + rainfall6) / 6 Display Average Display rainfall1 Display rainfall2 Display rainfall6 www.monash.edu.au 5 Motivation To calculate the average we need to read all the data To be able to display the average before displaying the rainfall amounts requires we retain the data Six months of rainfall Six individual variables – each has different name, same type Can’t use a loop to read them, because of the different names We Desire: An efficient means of storing data A generic approach to solving the problem, so that if it changes to 12 months we don’t have to add more code www.monash.edu.au 6 Introducing the Array An array stores a group of values of the one data type E.G. a group of integers, a group of Strings Individual elements of an array are distinct things As though they were a separate variable Identified by an index in addition to the name An Array is a data structure that: Allows us to collect together similar data Has a single name Has multiple containers, each have unique index.

Lecture Outline - Monash University · IMS1906 Programming in VB.NET Week 7 – Lecture 1 & 2 Arrays Part 1 and II ... type – Can’t use a ... we will have found the maximum 30

  • Upload
    lambao

  • View
    215

  • Download
    0

Embed Size (px)

Citation preview

www.monash.edu.au

IMS1906 Programming in VB.NETWeek 7 – Lecture 1 & 2

Arrays Part 1 and II

© Angela CarboneMonash University School of Information Management and Systems

www.monash.edu.au2

Lecture Outline

• Introduction to Arrays

• Defining Arrays (VB.NET)– Declaring and Initialising Array– Assigning values to Arrays– Properties and methods of

Array Class

www.monash.edu.au3

Motivation for arrays

• Much computer processing applies to sets of data

• Sets can be quite large• Example: Calculate average rainfall

Write a program which reads in the amount of rainfall for each of 6 months, displays the average rainfall followed by the individual monthly rainfall amounts.

www.monash.edu.au4

Rainfall Solution – Attempt 1

Read rainfall1Read rainfall2…Read rainfall6Average ß (rainfall1 + rainfall2 + rainfall3 + rainfall4 +

rainfall5 + rainfall6) / 6Display AverageDisplay rainfall1Display rainfall2…Display rainfall6

www.monash.edu.au5

Motivation

• To calculate the average we need to read all the data• To be able to display the average before displaying the

rainfall amounts requires we retain the data– Six months of rainfall– Six individual variables – each has different name, same

type– Can’t use a loop to read them, because of the different

names• We Desire:

– An efficient means of storing data– A generic approach to solving the problem, so that if it

changes to 12 months we don’t have to add more code

www.monash.edu.au6

Introducing the Array

• An array stores a group of values of the one data type– E.G. a group of integers, a group of Strings

• Individual elements of an array are distinct things– As though they were a separate variable– Identified by an index in addition to the name

• An Array is a data structure that:– Allows us to collect together similar data– Has a single name– Has multiple containers, each have unique index.

www.monash.edu.au7

Introducing the Array

Visualising an Array of Strings – days of the week:

Sunday Monday Tuesday Wednesday Thursday Friday Saturday

• The array has a name: DayNames• Each element has an index or subscript (an integer)• The name and index uniquely identifies an element

– E.g. DayNames( 2) has the value ‘Tuesday’• All elements in the array have the same data-type

DayNames:

0 1 2 3 4 5 6DayNames(3)

www.monash.edu.au8

Introducing the Array

• Number of elements grouped into array = Size of array• Use a number inside brackets after array name to specify

a particular element:e.g. DayNames(4) is the fifth element of array

• A Change to the value of one element does not affect any of the other elements

• The name combined with an index refers to an element – its type is ‘integer’ or ‘string’ or some other type

• The name by itself refers to the array as a whole– its type is ‘array of integers’, ‘array of Strings’, etc.

www.monash.edu.au9

Rainfall – Solution with Arrays

Process_RainfallSet sum to zeroDO index = 0 to 5

Read rainfall_amount (index)Set sum = sum + rainfall_amount (index)

END DOAverage = sum / 6Display AverageDO index = 0 to 5

Display rainfall_amount (index)END DO

END

www.monash.edu.au10

Array Solution - Comments

• Solution is able to use a loop structure– Simple to increase number of months

• Solution is easier to understand– Read a value, add that value to running total (sum)

• Solution is more concise– This solution is more efficient than the original

solution(Original solution would lose marks for efficiency)

www.monash.edu.au11

Using Arrays

• Arrays are useful in many cases:– Storing lists of related data– Affords the use of loop structures to process the data

• Need to declare arrays– Either at the module level or procedure level

• Need to initialise arrays– Populate them with initial data (from file, from user, etc.)

• Once initialised, can perform processing on arrays• Maybe store array elements out to a file• Maybe pass arrays between modules…

www.monash.edu.au12

Declaring Arrays in VB.NET

Dim strDayNames (6) As String

Name for the array

The upper bound of valid subscripts

The Data Type for items in

array

This declares a procedure-level Array named strDayNames that can store String elements. The elements are named dayNames(0) … dayNames(6)

www.monash.edu.au13

Declaring and Initialising Arrays (Examples)

Dim intRainfallAmounts(11) As Integerdeclares a 12-element procedural level array named intRainfallAmounts; each element is automatically initialised to the number zero

Dim decSales() As Decimal = {75.30D, 9.65D}declares and initialises a 2-element procedural level array named decSales;

Private strItems(9) As Stringdeclares a 10-element module level array named strItems ; each element is

automatically initialised to the keyword Nothing [Note variable initialised to nothing do not actually contain the word nothing, rather they contain no data at all]

Private mstrStates() As String = {“Vic”, “Qld”, “NSW”}declares and initialises a 3-element module level array named mstrStates;

www.monash.edu.au14

Declaring and Initialising Arrays

• When you declare an array, a default value is given to all elements

– Numeric data types à value 0– String data type à Empty String

• It is possible to list the desired initial values when declaring the array:

– No need to specify upper bound– Example:Dim strDayNames() As String = { “”, “Sunday”, _“Monday”, “Tuesday”, “Wednesday”, “Thursday”, _“Friday”, “Saturday” }

Value for strDayNames(0)

Value for strDayNames(4)

www.monash.edu.au15

Declaring Arrays

• Local Declaration – procedure/function-level– Dim appears inside sub procedure (or event procedure or

function)– values can be assigned only inside the procedure– memory is freed for re-use as soon as procedure is completed

• Global Declaration – form-level– Private appears in the (Form) (Declarations) section of code– values can be assigned anywhere in the form

> Typically initialise in the Form’s Load event procedure

– memory allocation (and values) are preserved between each event procedure call

www.monash.edu.au16

Variable Array Properties and Methods

• The ‘length’ property – tells how many items can be stored in an array:

Consider this array:Dim intNumbers(10) As IntegerintNumbers.length property will give the value 11 (index 0 is included)

• The ‘GetUpperBound’ method – tells the highest valid index for the array:

The Statement:intNumbers.GetUpperBound(0) will report the value 10, because this is the last valid index

– For 1D arrays, you must always include ‘0’ in the GetUpperBoundmethod call.

www.monash.edu.au17

Array Class

• Array.Sort method– Syntax

> Array.Sort(arrayname ), where array name is the name of the one-dimensional array to be sorted

> Eg: Array.Sort(intNumbers ) sorts numbers in ascending order

• Array.Reversemethod– Syntax

> Array.Reverse(arrayname ), where array name is the name of the one-dimensional array whose elements you want reversed

> Eg: Array.Reverse(intNumbers ) organises array elements in reverse order

[See Zak, p337]

www.monash.edu.au18

Rainfall Example in VB.NET

Dim intSum As Integer = 0, sngAverage As SingleDim intMonth As Integer

' The following line creates an array that can contain' 12 values of rainfallDim intRainfall(11) As Integer

' Read and store each month's rainfall' and add to intSumFor intMonth = 0 To 11

intRainfall(intMonth) = InputBox("Enter Rainfall " & intMonth)intSum = intSum + intRainfall(intMonth)

Next intMonth

www.monash.edu.au19

Rainfall Example in VB.NET (cont)

' Calculate Average, and display messagesngAverage = intSum / 12OutputListbox.Items.Add( "The average rainfall was " & _

Format(sngAverage, "Fixed"))

' Display each month’s rainfall amount in a listbox. Use a ‘ new loop, to step through each element.For intMonth = 0 To 11

OutputListbox.Items.Add( _"Month " & CStr(intMonth) & _", Rainfall: " & CStr( intRainfall(intMonth)) )

Next intMonth

www.monash.edu.au20

Summary

• Declaring and Initialising Arrays– Dim statement – procedure level– Private statement – module level

• Assigning values to arrays• Array properties and methods

– Length property– GetUpperBound(0) method– Array.Sort(arrayname) method– Array.Reverse(arrayname) method

www.monash.edu.au21

Summary/Reading

• An Array is a data structure that:– Allows us to collect together similar data– Has a single name– Has multiple slots, each with a unique index or subscript– The values in the slots are called elements– All elements are of the same data type

• A one-dimensional array is an array where we can specify any valid element by giving:

– The array’s name– A single index, inside round-brackets. Eg:

dayOfWeek(4) refers to the fifth element in dayOfWeek

• Reading– Zak, Chapter 9, p324-343– Unit Guide, Study Guide 8– Robertson, Chapter 7, p88-101

• Review Questions– Zak, p358 Q1, Q3-Q6, Q12– Zak, p362 Q1-Q5

www.monash.edu.au

IMS1906 Programming in VB.NETWeek 10 – Lecture 2

Arrays Part II

© Angela CarboneMonash University School of Information Management and Systems

www.monash.edu.au23

Outline

• Resizing arrays• Searching an unsorted array

www.monash.edu.au24

Motivation to resize the array

Scenario:

Write a program that asks for the number of students in a class, then reads the names of those students into an array.

Problems:• How do we know how much space the array

needs?• How can we cope with larger amounts of data than

expected?

www.monash.edu.au25

Dynamic Sizing of Arrays

• Arrays can have their size changed– Called Re-Dimensioning

• Arrays do not need to be given an initial size when declared:

Dim strNames( ) As String– Specifies that strNames is an Array variable– Specifies that the elements of strNames must be Strings

– But does not say how many elements there will be> Initially, there are no elements

• Size of array can be changed more than once

• Dynamic means decided at run-time instead of coding -time

www.monash.edu.au26

The ReDim statement

• To change the size of a declared array, use ReDim• Do not need to specify As Datatype

– The data type of the elements cannot be changed

• Example:ReDim strNames(19)

– Allocates enough space for 20 names (indexes 0 to 19)

• ReDim will then initialise all values to default values – 0 or empty string

• ReDim can only appear inside Sub or Function procedures

– Dim statements can appear outside of Sub/Functions, in Form level

www.monash.edu.au27

ReDim – Preserving existing data

• To preserve any existing data elements, must include the Preserve clause:ReDim Preserve strNames(29)

– Expands the array to contain a total of 30 elements– Keeps the values of elements 0-19– Initialises the values of elements 20-29 to default

value (empty)• To shrink the array:

ReDim Preserve strNames(15)

www.monash.edu.au28

Motivation for searching through array

• Imagine you have an array of temperatures recorded over the period of a month

• Things you may want to do with the temperatures:– Determine what the highest temperature was– Determine when the highest temperature was– Similar for the lowest temperature– Determine when (or indeed if) it was 22 degrees.– Determine how many times it was 18 degrees.

• These are typical array problems which can be classified as search problems.

www.monash.edu.au29

Finding a maximum value

• To find the highest temperature, need to consider all elements of the array

• Initially, only first temperature known, so it is the highest we know of

• Consider each element in turn:– If it is lower than the highest we’ve seen so far, ignore it– If it is higher than the highest we had previously seen,

take note of this new element.• After considering all elements, we will have found the

maximum

www.monash.edu.au30

Algorithm – Finding Maximum

‘Assume elements on the array are stored starting at ‘position index 1

posOfHighestValue = 1highestValue = array(1)

curElementPos = 2 (we’ve already looked at pos 1)

DO WHILE curElementPos <= numOfElementsIF array(curElementPos ) > highestValue THEN

highestValue = array(curElementPos ) posOfHighestValue = curElementPos

END IFincrement curElementPos

END DO

www.monash.edu.au31

Illustration: Finding Maximum

16 13 18 17Temperature:

1 2 3 4

posOfHighestValue:

highestValue:

curElementPos:

Temperature(curElementPos):

www.monash.edu.au32

16 13

Illustration: Finding Maximum

16 13 18 17Temperature:

1 2 3 4

posOfHighestValue:

highestValue:

curElementPos:1

16

2

Temperature(curElementPos): 13

Is temperature(curElementPos) > highestValue ?

No, so move to next position

www.monash.edu.au33

16

18

3

13

Illustration: Finding Maximum

16 17Temperature:

1 2 3 4

posOfHighestValue:

highestValue:

curElementPos:1

16 Temperature(curElementPos):

Is temperature(curElementPos) > highestValue ?

Yes, so update LHS variables

18

www.monash.edu.au34

16

18

3

13

Illustration: Finding Maximum

16 17Temperature:

1 2 3 4

posOfHighestValue:

highestValue:

curElementPos:3

18 Temperature(curElementPos):

Is temperature(curElementPos) > highestValue ?Yes, so update LHS variables

18

Then move to next position…

www.monash.edu.au35

16

17

4

13

Illustration: Finding Maximum

16 17Temperature:

1 2 3 4

posOfHighestValue:

highestValue:

curElementPos:3

18 Temperature(curElementPos):

Is temperature(curElementPos) > highestValue ?

18

No, so move to next positionBut no more positions, so we are

finishedwww.monash.edu.au

36

Searching Arrays

• Simple/Linear Search:– When we consider all elements one by one in an

unsorted array (just shown)– Consider elements one by one (iterative process)– Perform a comparison to try and get a match– To find largest/smallest, must go through whole

array

www.monash.edu.au37

Summary/Reading

• Re-dimensioning array– Sometimes size of array not known at coding time– VB allows you to specify size at runtime – “dynamic”

• Linear Searching Arrays• Reading

– Zak, Chapter 9, p332-337-343– Unit Guide, Study Guide 8 [NOTE- Chapter 9 of the

Unit Guide is NOT covered in ims1906.]– Robertson, Chapter 7, p88-101