150 likes | 240 Views
12: One-dimensional Arrays. Declaration. An array is a consecutive group of memory locations that have the same name and type. Their declaration will include an explicit indication of the size of the array or the means to infer its size. E.g. Dim marks(5) As integer
E N D
Declaration An array is a consecutive group of memory locations that have the same name and type. Their declaration will include an explicit indication of the size of the array or the means to infer its size. E.g.Dim marks(5) As integer This indicates to the compiler that 6 memory locations should be reserved for an integer array called marks. The first element of an array has a position number 0. On declaration, the upper bound (i.e. the highest index number) of the array is specified (not the actual size). Several arrays (or variables) may be declared in the same line: E.g. Dim x(6) As Integer, s(24) As String 2
Array data types An array can hold any data type • Primitive data type, e.g. • Integer • Double • Boolean • ADTs, e.g. • Controls - Button,TextBox • VB library - Random • User-defined - Circle,Square,Account The only constraint is that all the elements in an array must be of the same type 3
Initialisation Arrays may be initialised on declaration, E.g. Dim age( ) As Integer = { 23, 54, 96, 13, 7, 32} Here the size of the array is not specified but is inferred by the number of initial values. • By default • numeric array elements are initialised to zero • String to “” • Objects to Nothing. • Alternatively a programmer may explicitly initialise the array using assignment statements. Dim age(5) As Integer age(0) = 23 age(1) = 54 age(2) = 96 age(3) = 13 age(4) = 7 age(5) = 32 4
Referencing To reference a particular element of the array, its name and position number are specified. E.g. the fourth element of marks array is referred to by: marks(3) The position number contained within brackets is more formally called anindex. Sometimes it is useful to use a variable value as anindex.Such variables are usually declaredto beInteger. The Functions LBound and Uboundtake an array as their argument and return the lowest and highest numbered index value respectively. These are useful to determine the length of an array and ensure an index remains within its declared range. 5
E.g. Loops involving arrays The following accumulates a set of marks: This is equivalent to the following which uses a while loop: Dim std As integer Dim total As integer = 0 For std = LBound(marks)to UBound(marks) total += marks(std) Next Dim total As integer = 0 Dim std As Integer = 0 Do while std < UBound(marks) total += marks(std) std += 1 Loop 6
Methods and properties All arrays have access to the methods and properties of System.Arrayclass. E.g. • Length – returns the total number of elements in the array • getUpperBound(0) - returns the upper bound of the one-dimensional array • Sort - sorts the array in an ascending order 8
2 1 3 2 4 3 4 1 Methods and properties – cont’d E.g. • Dim size, highestIndexNo As Integer • Dim myArray() As Integer = {2, 3, 4, 1} • size = myArray.Length • highestIndexNo = myArray.GetUpperBound(0) • Array.Sort(myArray) myArray size 4 highestIndexNo 3 myArray 9
Example: using arrays Listing days of the week: cmdShow method Private Sub cmdShow_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles cmdShow.Click Dim weekDays() As String = {"Monday", "Tuesday", "Wednesday", _ "Thursday", "Friday"} Dim i As Integer lstBox.Items.Add("Index Day") For i = 0 To weekDays.getUpperBound(0) lstBox.Items.Add(CStr(i) & Tab&weekDays(i)) Next End Sub 10
Change array size Once an array is created • its length/size is fixed • its index ranges from 0 to its upper bound When a program is executed, Visual Studio automatically performs bounds checking to ensure the program does not attempt to access data outside the bounds of an array. Referencing array elements outside the array bounds causes a runtime error. • ReDim– is used to change the length/size of an array at run-time, i.e. as a program executes. 11
Changing array size - cont’d E.g. • Dim weekDays() As String = { "Monday", "Tuesday", "Wednesday", _ • "Thursday", "Friday" } weekDays.Lengthis5 weekDays.GetUpperBound(0) is4 • ReDim Preserve weekDays(6) • weekDays(5) = "Saturday" • weekDays(6) = "Sunday" The keyword Preserveensures that data stored in the array are retained. weekDays.Lengthis7 weekDays.GetUpperBound(0) is6 12
Passing Arrays An array is passed to a method or function by including the array name in the argument list.E.g. Dim marks(5) As Integer CalculateStats(marks)A single array element may also be passed by simply specifying the array element in the procedure’s argument list.E.g. TopMark(marks(3)) For a method to receive an array through a call, the parameter list must indicate that an array will be received.E.g. Private Sub useArray( ByVal x( ) As Integer ) Note the size of the array is not specified between the brackets. 13
Passing Arrays - cont’d E.g. Calculate the average course mark: • Dim courseMarks() As Integer = {85, 70, 90, 65} • Dim mean As Double • mean = Average(courseMarks) • MessageBox.Show(" Mean: " & CStr(mean) ) • Private Function Average(ByValarr() As Integer) As Double • Dim i As Integer • Dim totalValue As Integer = 0 • Dim totalNo As Integer = arr.Length • For i = 0 To totalNo - 1 • totalValue+= arr(i) • Next • Return Math.Round( totalValue / totalNo, 1) • End Function The size of the array is not specified. 14
Summary • An array is a collection of data with a single name • All the elements in an array are of the same type • The index of an array starts at 0 • All arrays have access to methods and properties of System.Arrayclass, e.g. • Length • getUpperBound(0) • Sort • Referencing array elements outside the array bounds causes a runtime error • The size of an can be changed at run-time using ReDim 15