IS 350 Arrays.

Slides:



Advertisements
Similar presentations
Pemrograman VisualMinggu …7… Page 1 MINGGU Ke Tujuh Pemrograman Visual Pokok Bahasan: Arrays Tujuan Instruksional Khusus: Mahasiswa dapat menjelaskan.
Advertisements

Programming Logic and Design Sixth Edition
Microsoft Visual Basic 2010: Reloaded Fourth Edition
VBA Modules, Functions, Variables, and Constants
Case, Arrays, and Structures. Summary Slide  Case Structure –Select Case - Numeric Value Example 1 –Select Case - String Value Example  Arrays –Declaring.
Chapter 8. 2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays as Arguments Two-Dimensional Arrays Common.
C++ for Engineers and Scientists Third Edition
Chapter 8 Arrays and Strings
Chapter 8 Using Repetition with Loops and Lists. Class 8: Loops and Lists Write Do loops to execute statements repeatedly Write For loops to execute statements.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 l Array Basics l Arrays in Classes and Methods l Programming with Arrays.
Chapter 7: Arrays. In this chapter, you will learn about: One-dimensional arrays Array initialization Declaring and processing two-dimensional arrays.
IE 212: Computational Methods for Industrial Engineering
Visual Basic 2010 How to Program © by Pearson Education, Inc. All Rights Reserved.
Microsoft Visual Basic 2008 CHAPTER NINE Using Arrays and File Handling.
 2004 Prentice Hall, Inc. All rights reserved. 1 Chapter 11 - JavaScript: Arrays Outline 11.1 Introduction 11.2 Arrays 11.3 Declaring and Allocating Arrays.
A First Book of ANSI C Fourth Edition
Chapter 8 Arrays and Strings
 2008 Pearson Education, Inc. All rights reserved JavaScript: Arrays.
Introduction to Arrays in Java Corresponds with Chapter 6 of textbook.
Arrays and 2D Arrays.  A Variable Array stores a set of variables that each have the same name and are all of the same type.  Member/Element – variable.
4 1 Array and Hash Variables CGI/Perl Programming By Diane Zak.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2009 Pearson Education, Inc., Upper.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Java Script: Arrays (Chapter 11 in [2]). 2 Outline Introduction Introduction Arrays Arrays Declaring and Allocating Arrays Declaring and Allocating Arrays.
Lecture Set 9 Arrays, Collections and Repetition Part C - Random Numbers Rectangular and Jagged arrays.
C++ for Engineers and Scientists Second Edition Chapter 11 Arrays.
Section 5 - Arrays. Problem solving often requires information be viewed as a “list” List may be one-dimensional or multidimensional List is implemented.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: One-Dimensional Arrays Array Initialization Arrays.
Chapter 9 Processing Lists with Arrays. Class 9: Arrays Understand the concept of random numbers and how to generate random numbers Describe the similarities.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
Programming with Microsoft Visual Basic 2012 Chapter 9: Arrays.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Arrays Chapter 7. MIS Object Oriented Systems Arrays UTD, SOM 2 Objectives Nature and purpose of an array Using arrays in Java programs Methods.
Arrays Declaring arrays Passing arrays to functions Searching arrays with linear search Sorting arrays with insertion sort Multidimensional arrays Programming.
SEQUENTIAL AND OBJECT ORIENTED PROGRAMMING Arrays.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Arrays.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 7A Arrays (Concepts)
A FIRST BOOK OF C++ CHAPTER 7 ARRAYS. OBJECTIVES In this chapter, you will learn about: One-Dimensional Arrays Array Initialization Arrays as Arguments.
Arrays 1.
7.1 Introduction Arrays Arrays are data structures consisting of data items of the same type “Static” entities They remain the same size once they are.
Arrays Chapter 7.
Chapter 11 - JavaScript: Arrays
Arrays Chapter 7.
An Introduction to Programming with C++ Sixth Edition
Chapter 7: Working with Arrays
Computer Programming BCT 1113
Microsoft Visual Basic 2005: Reloaded Second Edition
Array, Strings and Vectors
Visual Basic 2010 How to Program
Chapter 7: Array.
JavaScript: Functions.
IS 350 Loops.
Arrays, Collections and Repetition Part A – Arrays and Repetition
VBScript Session 2 Dani Vainstein.
7 Arrays.
CNG 140 C Programming (Lecture set 8)
EKT150 : Computer Programming
JavaScript Arrays.
Lecture Set 9 Arrays, Collections and Repetition
Arrays.
Data Structures (CS212D) Week # 2: Arrays.
Arrays Chapter 7.
Arrays Week 2.
VBScript Session 2 Dani Vainstein.
CIS16 Application Development and Programming using Visual Basic.net
7 Arrays.
C++ Array 1.
Introduction to Computer Programming IT-104
Arrays.
Presentation transcript:

IS 350 Arrays

Objectives Understand the concept of random numbers and how to generate them Describe the similarities and differences between arrays and collections Declare arrays and use Do loops and For loops to examine array elements Sort, reverse, and search for elements in an array Find and diagnose common array errors Work with multidimensional arrays and arrays of objects 2

Introduction to Random Numbers Many applications require the use of random numbers Gaming applications Computer simulations Creating test data 3

Random Number Generation A random number generator is initialized based on a seed value Given the same seed value, the same random number sequence will be generated Different seed values will generate different random number sequences The time of day is often used to create random seed values

The System.Random Class The System.Random class is used to create a random number generator and get random values The constructor creates the random number generator Without arguments, a random seed value is used The seed value is based on the time of day Dim RandomSeed As New Random() With an argument, a constant seed value is used Dim FixedSeed As New Random(10)

The Next Method Without arguments, the Next method gets a positive random Integer value Dim RandomValue As Integer RandomValue = RandomSeed.Next() With two arguments, a value within a range is returned The first argument contains the lower bound and the second argument contains the upper bound (exclusive) RandomValue = RandomSeed.Next(1, 10)

The NextDouble Method The NextDouble method returns a random value between 0.0 and 1.0 Example: Dim RandomDouble As Double RandomDouble = _ RandomSeed.NextDouble()

Generating many Random Values Most often, a sequence of random numbers is generated rather than just one Example to add random values to a list box: Dim CurrentRandom As New System.Random() Dim CurrentIndex As Integer Dim CurrentRandomValue As Double For CurrentIndex = 1 To 100 CurrentRandomValue = _ CurrentRandom.NextDouble() lstRandomList.Items.Add( _ CurrentRandomValue.ToString()) Next

Introduction to Arrays Chapter 8 introduced the concept of a collection (list) This chapter introduces the concept of an array Lists and arrays have similarities and differences Both arrays and instances of the List class store multiple items having the same data type The size of both lists and arrays can be changed at run time The Add and RemoveAt methods work with lists An array's size is changed through a process called redimensioning

Characteristics of Arrays An array stores multiple data items, each having the same data type An array can store a list of values having primary data types or other data types An array of integers or text boxes, for example An array has one or more dimensions A one-dimensional array can be thought of as a list A two-dimensional array can be thought of as a grid or table A three-dimensional array can be thought of as a cube

Characteristics of Arrays (continued) The number of dimensions in an array is called the rank A one-dimensional array has a rank of 1 A two-dimensional array has a rank of 2 Each data item stored in an array is called an element An array element is referenced by a unique index value called a subscript One subscript is used to reference elements in a one-dimensional array Two subscripts are used to reference elements in a two-dimensional array

The Array Class (members) The Length property gets the number of elements in the array The Length property is 1-based The Rank property gets the number of dimensions A one-dimensional array has a Rank of 1 The GetLength method gets the number of array elements in a particular dimension The 0-based array dimension is passed as an argument The GetUpperBound and GetLowerBound methods get the largest and smallest subscript for a dimension These methods are 0-based The array dimension is passed as an argument The Sort method sorts an array or part of an array

Common Array Tasks Arrays must be declared just as any variable must be declared It is possible to declare and initialize an array in the same statement It is possible to determine the bounds of an array An array's size can be changed at run time Data must be stored and retrieved to and from array elements

Declaring Arrays (syntax) [Public | Friend | Private | Dim] arrayName([size]) As dataType = initExpr The access modifier (Public, Friend, Private) defines the array's visibility The identifier (name) is defined by arrayName The optional size contains the value of the largest subscript The size argument is 0-based Omit the size to declare a dynamic uninitialized array dataType defines the data type of the array’s elements initExpr is used to assign initial values to the array's elements

Declaring Arrays (examples) Declare an uninitialized one-dimensional array Dim EmptyArray() As Integer Declare a one-dimensional array with one element Dim OneElementArray(0) As Integer Declare a one-dimensional array with four elements Dim SingleArray(3) As Single

Implementation of Arrays The Array class is a reference type Thus, any array variable stores the memory address of the actual array An uninitialized array has a value of Nothing

How memory is allocated to an array

Initializing an Array An array can be initialized when it is declared The initialization list appears in braces ({}) A comma separates each initialization value The array must be dynamic (declared without an initial subscript value)

Initializing an Array (example) Declare and initialize a Double array with four elements: Dim QuarterlySalesAmounts() As Double = _ {240.92, 128.43, 347.55, 420.77}

Declaring and initializing an array

Declaring and Initializing Boolean and String Arrays Declare and initialize a Boolean array Dim WeekDayArray() As Boolean = _ {False, True, True, True, True, True, False} Declare and initialize a String array Dim MonthNames() As String = _ {"January", "February", "March", "April", "May", _ "June", "July", "August", "September", _ "October", "November", "December"}

Declaring and initializing an array of strings

Determining an Array's Bounds The GetUpperBound method gets the largest subscript for a particular dimension It returns the largest subscript not the number of elements The GetLowerBound method gets the smallest subscript for a particular dimension The 0-based dimension is passed as an argument to each method The methods will throw an exception if the array dimension does not exist

Determining an Array's Bounds (Examples) Get the lower and upper bound of the first array dimension for the array named MonthNames Dim SmallestSubscript, _ LargestSubscript As Integer SmallestSubscript = _ MonthNames.GetLowerBound(0) ' 0 LargestSubscript = _ MonthNames.GetUpperBound(0) ' 12

Redimensioning an Array An array's size is determined by the number of dimensions in the array and the number of elements in each dimension An array is redimensioned with the ReDim statement Arrays must be redimensioned when the initial size is not known

The ReDim Statement (Syntax) ReDim [Preserve] varname(size) The ReDim statement redimensions an array The ReDim statement is an executable statement It must appear inside of a procedure The optional Preserve keyword preserves the array's contents There are restrictions on the use of the Preserve keyword varname contains the name of the array to redimension size contains the new array size

Redimensioning an Array (Example) Declare an array Dim IntegerList() As Integer = _ {24, 12, 34, 42} Redimension the array (increasing the size by one to five elements) ReDim IntegerList(4) Redimension the array and preserve its contents ReDim Preserve IntegerList(4)

Redimensioning an array

Performing Assignment Statements with Arrays Assignment statements using arrays require a subscript The subscript appears in parentheses following the array name The data types of the left and right side of the assignment statement must be compatible

Performing Assignment Statements with Arrays (examples) Declare an array with 13 elements (subscript values from 0 to 12) Dim MonthlySalesAmounts(12) As Double Store and retrieve a value from the second array element (a subscript value of 1) Dim CurrentMonthlySalesAmount As Double MonthlySalesAmounts(1) = 84616.12 CurrentMonthlySalesAmount = _ MonthlySalesAmounts(1)

Storing and retrieving array values

Type Conversion and Arrays Explicit type conversion of array elements is possible Call methods of the System.Convert class or call the ToString method to convert an element to a string Convert an array element (Double) to a string Dim OutputString As String OutputString = MonthlySalesAmounts(1).ToString() Convert a String to a Double and store the result in an array element MonthlySalesAmounts(1) = _ ToDouble(txtSalesAmount.Text)

Type Conversion and Arrays (Errors) Use care to apply the subscript when working with arrays The following statement is missing a subscript and will return the data type of the array's elements: OutputString = SalesList.ToString() Example output: System.Double[]

Variables and Array Subscripts Variables are often used as array subscripts Especially when using loops to examine all the elements in an array Variables used as subscripts must have an integral data type

Variables and Array Subscripts (example) Reference an array element with a variable as a subscript: Dim SubscriptValue As Integer = 1 Dim SalesListItem As Double SalesListItem = _ MonthlySalesAmounts(SubscriptValue)

Using Loops to Examine Array Elements Common array tasks involving loops Calculate the total value of all array elements using an accumulator Calculate the minimum value stored in an array Calculate the maximum value stored in an array Calculate the average value of the elements in an array

Using a loop to examine array elements and calculate their total value

Examine an Array's Elements (example) Tally the values of an array's elements. AnnualSalesTotal contains the total value Dim AnnualSalesTotal As Double = 0.0 Dim Counter As Integer = 1 Do While Counter <= _ MonthlySalesAmounts.GetUpperBound(0) AnnualSalesTotal += _ MonthlySalesAmounts(Counter) Counter += 1 Loop

Determining the Minimum Value of an Array’s Elements First, initialize the current minimum value Use the value of the first array element or Use the largest value for the underlying data type Use a loop to find the current minimum value comparing the current minimum value with the current array element’s value Replace the current minimum value, if necessary

Determining the Minimum Value of an Array Element (example) Find the minimum value in the array named MonthlySalesAmounts The first element is not used in the example Dim Counter As Integer = 1 Dim CurrentMinimum As Double = _ MonthlySalesAmounts(Counter) For Counter = 1 To _ MonthlySalesAmounts.GetUpperBound(0) If MonthlySalesAmounts(Counter) < _ CurrentMinimum Then CurrentMinimum = _ End If Next

Determining the Maximum Value of an Array Element The process is nearly the same as finding the minimum value The condition in the decision-making statement is reversed Initialize the current maximum value to the value of the first element or the maximum value for the data type

Determining the Maximum Value of an Array Element (example) Find the maximum value in the array named MonthlySalesAmounts Note the first array element is not used in the example Dim Counter As Integer = 1 Dim CurrentMaximum As Double = _ MonthlySalesAmounts(Counter) For Counter = 1 To _ MonthlySalesAmounts.GetUpperBound(0) If MonthlySalesAmounts(Counter) > _ CurrentMaximum Then CurrentMaximum = _ End If Next

Determining the Average Value of an Array's Elements Using an accumulator, tally the value of all array elements Divide the total value by the number of array elements to determine the average

Arrays as Function Arguments An array can be passed to a procedure as an argument In the Function declaration, declare the argument with parentheses in the same way a dynamic array is declared Example: Public Shared Function Total( _ ByVal argList() As Double) As Double End Function

Sorting Array Elements Use the Sort method of the System.Array class to sort array elements Example: Private SampleArray() As Double = _ {6.11, 4.12, 5.88, -6.44} System.Array.Sort(SampleArray) Example output: -6.44, 4.12, 5.88, 6.11

Sorting Array Elements (continued) It's possible to sort part of an array Call the Sort method with additional arguments The first argument contains the array to sort The second argument contains the starting array subscript The third argument contains the subscript of the last element to sort

Sorting Array Elements (continued) Sort the array named SampleArray excluding the first element Private SampleArray() As Double = _ {0, -6.44, 4.12, 5.88, 6.11} System.Array.Sort(SampleArray, 1, _ SampleArray.GetUpperBound(0))

Sorting part of an array

Reversing Array Elements Calling the Reverse method of the System.Array class reverses the order of an array’s elements It's possible to reverse all array elements or a range of elements The arguments to the Reverse method are the same as the arguments to the Sort method Example: System.Array.Reverse(SampleArray)

Introduction to Searching It's often necessary to search for an array element Searching can be performed in different ways A sequential search examines each element, in order, until the element is found or the entire array has been searched A sorted array can be efficiently searched using a binary search

Using a Sequential Search A sequential search works on an unordered (unsorted) array Each element is examined sequentially using a loop If the item is found, the loop exits If all elements are examined, the item is not found and the loop exits Use the IndexOf method to search for an array element First argument contains the array name Second argument contains the search value

Using a Binary Search If an array is sorted, a binary search can be used to find an array element The performance is much better than a sequential search Call the BinarySearch method instead of the IndexOf method First argument contains the array name Second argument contains the search value

Using a Binary Search (example) Private SampleArray() As Double = _ {-6.44, 4.12, 5.88, 6.11} Dim SearchValue As Double = 5.88 Dim ArrayElement As Integer ArrayElement = System.Array.BinarySearch( _ SampleArray, _ SearchValue)

Comparisons using a binary search

Common Array Errors Errors are commonly made when processing arrays Forgetting to include a subscript Dim DemoArray(12) As Integer DemoArray = 100 Subscript out of range errors Dim DemoArray(12) As Double For Counter = 0 To 24 Total += DemoArray(Counter) Next

Introduction to Two-dimensional Arrays A two-dimensional array has rows and columns Conceptually, it's similar to a grid or table Two-dimensional arrays have two subscripts instead of one Declare a dynamic two-dimensional array Dim Table(,) As Integer Declare a two-dimensional array with 4 rows and 5 columns (20 elements) Dim SalesArray(3, 4) As Integer

Initializing Two-dimensional Arrays Two-dimensional arrays can be initialized just as one-dimensional arrays can be initialized The array must not be given an initial size The initialization list is nested as follows: Private SalesArray(,) As Integer = { _ {150, 140, 170, 178}, _ {155, 148, 182, 190}, _ {162, 153, 191, 184}, _ {181, 176, 201, 203} _ }

Table 9-1 Sample sales data

Referencing Elements in a Two-dimensional Array Two-dimensional arrays require two subscripts instead of one A comma separates the two subscripts Reference the third row and fourth column in the array named SalesArray Dim Cell As Integer Cell = SalesArray(2, 3)

Referencing an element in a two-dimensional array

Introduction to Three-dimensional Arrays It's possible to create arrays with three dimensions A three-dimensional array has three subscripts instead of two Declare a dynamic three-dimensional array Dim Cube(,,) As Integer Declare a 3 by 3 by 3 array (9 elements) Dim TicTacToeBoard(2, 2, 2) As String

Referencing an element in a three-dimensional array

Working with Arrays of Objects Arrays can store object references in addition to storing primary data types Example to store text box references Dim TextBoxList(2) As TextBox TextBoxList(0) = txtLogID TextBoxList(1) = txtLogStartTime TextBoxList(2) = txtLogEndTime

Memory allocation to store an array of text boxes

Chapter Summary Simulations require the use of random numbers The System.Random class implements random numbers The Next method gets a random integral value The NextDouble method gets a random floating-point value Arrays store a list of values instead of a single (scalar) value Arrays have one or more dimensions Reference an element using a subscript Call GetLowerBound and GetUpperBound to get the largest subscript for a particular dimension Multidimensional arrays have one or more dimensions