To store a single number you would declare one Integer variable. To store three numbers you would need three variables:

Similar documents
One Dimension Array: Declaring a fixed-array, if array-name is the name of an array

Company Setup 401k Tab

Visual Basic Programming. An Introduction

Many applications consist of one or more classes, each containing one or more methods. If you become part of a development team in industry, you may

VB.NET Programming Fundamentals

EET 310 Programming Tools

Notes on Excel Forecasting Tools. Data Table, Scenario Manager, Goal Seek, & Solver

Hands-On Lab. Building a Data-Driven Master/Detail Business Form using Visual Studio Lab version: Last updated: 12/10/2010.

Quosal Form Designer Training Documentation

TRANSITION FROM TEACHING VB6 TO VB.NET

Visual Basic 2010 Essentials

Sample Table. Columns. Column 1 Column 2 Column 3 Row 1 Cell 1 Cell 2 Cell 3 Row 2 Cell 4 Cell 5 Cell 6 Row 3 Cell 7 Cell 8 Cell 9.

Excel Reports and Macros

Ofgem Carbon Savings Community Obligation (CSCO) Eligibility System

Excel -- Creating Charts

Lecture 2 Mathcad Basics

The VB development environment

Excel & Visual Basic for Applications (VBA)

UNIVERSITY OF CALGARY Information Technologies WEBFORMS DRUPAL 7 WEB CONTENT MANAGEMENT

Using the For Each Statement to 'loop' through the elements of an Array

ITS Training Class Charts and PivotTables Using Excel 2007

Introduction to Custom GIS Application Development for Windows. By: Brian Marchionni

Designing a Graphical User Interface

Styles, Tables of Contents, and Tables of Authorities in Microsoft Word 2010

MICROSOFT ACCESS STEP BY STEP GUIDE

FORM FRAMEWORX. SharePoint 2013 App

LabVIEW Day 6: Saving Files and Making Sub vis

AP Computer Science Java Mr. Clausen Program 9A, 9B

DATA 301 Introduction to Data Analytics Microsoft Excel VBA. Dr. Ramon Lawrence University of British Columbia Okanagan

During the process of creating ColorSwitch, you will learn how to do these tasks:

ClientAce WPF Project Example

FrontPage 2003: Forms

TECHNOLOGY Computer Programming II Grade: 9-12 Standard 2: Technology and Society Interaction

EXCEL Tutorial: How to use EXCEL for Graphs and Calculations.

Microsoft Access Database

MICROSOFT EXCEL STEP BY STEP GUIDE

Integrating Microsoft Word with Other Office Applications

Presentations and PowerPoint

UCINET Quick Start Guide

0 Introduction to Data Analysis Using an Excel Spreadsheet

Advanced Microsoft Excel 2010

Using Pivot Tables in Microsoft Excel 2003

In-Depth Guide Advanced Spreadsheet Techniques

How To Analyze Data In Excel 2003 With A Powerpoint 3.5

Creating and Formatting Charts in Microsoft Excel

Organizing image files in Lightroom part 2

How to Excel with CUFS Part 2 Excel 2010

EXCEL 2007 VLOOKUP FOR BUDGET EXAMPLE

Python Lists and Loops

Scripting with CAMMaster And Visual Basic.NET

SPSS (Statistical Package for the Social Sciences)

To launch the Microsoft Excel program, locate the Microsoft Excel icon, and double click.

CONTENTM WEBSITE MANAGEMENT SYSTEM. Getting Started Guide

Hands-on Exercise 1: VBA Coding Basics

Answers to Review Questions Chapter 7

EDIT202 PowerPoint Lab Assignment Guidelines

Microsoft Excel 2007 Level 2

Call Centre Helper - Forecasting Excel Template

Final Examination Semester 2 / Year 2011

Sample. LabVIEW TM Core 1 Course Manual. Course Software Version 2010 August 2010 Edition Part Number B-01

Statgraphics Getting started

Summary of important mathematical operations and formulas (from first tutorial):

Prism 6 Step-by-Step Example Linear Standard Curves Interpolating from a standard curve is a common way of quantifying the concentration of a sample.

HOUR 3 Creating Our First ASP.NET Web Page

User Guide for the Junior Lab Scheduling Software

Appendix K Introduction to Microsoft Visual C++ 6.0

Excel Tutorial. Bio 150B Excel Tutorial 1

How to test and debug an ASP.NET application

SafeGuard PrivateCrypto 2.40 help

Creating Reports Using Crystal Reports

Microsoft Excel 2010 Charts and Graphs

Management Information Systems 260 Web Programming Fall 2006 (CRN: 42459)

Microsoft PowerPoint 2010 Computer Jeopardy Tutorial

Creating A Drip Campaign

LabVIEW Day 1 Basics. Vern Lindberg. 1 The Look of LabVIEW

WESTMORELAND COUNTY PUBLIC SCHOOLS Integrated Instructional Pacing Guide and Checklist Computer Math

Excel 2007 Basic knowledge

Composite.Community.Newsletter - User Guide

Access Tutorial 1 Creating a Database

This activity will show you how to draw graphs of algebraic functions in Excel.

Beginner s Matlab Tutorial

Changing the Display Frequency During Scanning Within an ImageControls 3 Application

Moving from C++ to VBA

Creating Database Tables in Microsoft SQL Server

Analytics Canvas Tutorial: Cleaning Website Referral Traffic Data. N m o d a l S o l u t i o n s I n c. A l l R i g h t s R e s e r v e d

Access Tutorial 2: Tables

Introduction to the Visual Studio.NET IDE

Named Memory Slots. Properties. CHAPTER 16 Programming Your App s Memory

Computer Skills Microsoft Excel Creating Pie & Column Charts

Instructions for creating a data entry form in Microsoft Excel

Excel 2003 A Beginners Guide

Microsoft Office PowerPoint Creating a new presentation from a design template. Creating a new presentation from a design template

Windows XP Pro: Basics 1

Flash Objects. Dynamic Content 1

Creating a Database in Access

Google Sites: Site Creation and Home Page Design

Excel 2007 A Beginners Guide

Excel 2003: Ringtones Task

SPSS Manual for Introductory Applied Statistics: A Variable Approach

About PivotTable reports

Transcription:

Part 1 Basic Topics Chapter 10 Arrays What is an array? To store a single number you would declare one Integer variable. To store three numbers you would need three variables: Dim FirstNumber, SecondNumber, ThirdNumber As Integer What about storing hundreds or even thousands of numbers? Clearly things get difficult if not impossible! An array is a data structure that stores as many items as you require using a single variable. All the items must be the same data type. Thus you can store an array of Integers, an array of Strings and so on. The only way to mix the data types is to store records in the array, but this is the subject of the next chapter. You have already used the array data structure, probably without realising it. For example in program 2.1 you used the SelectedIndex property of a list box to identify which item in the list box is the currently selected one. Visual Basic numbers the items from 0. So if you had a list box named lstemployees, Visual Basic.NET stores the 4 th item as lstemployees(3). How to declare an array To declare an array that can store 5 whole numbers you would write the following: Dim Numbers(4) As Integer The storage slots in the array are called subscripts. In figure 10.1 the variable Numbers stores all the data in the array. Numbers(1), for example, refers to the contents of subscript 1, i.e. 78, and Numbers(4) to 65. 0 1 2 3 4 56 78 42 80 65 Numbers(1) Numbers(4) Figure 10.1: An array holding 5 integers Earlier versions of Visual Basic allowed you to start the indexing of an array from values other than 0 but this is not now supported. Static and Dynamic arrays A static array is one whose size is fixed throughout the program. A dynamic array can grow and shrink in size as the program runs. First declare the array without indicating its size by using empty brackets. Then ReDim it with the required size at the point in your code where you want it to change. For example: 112

Chapter 10 Arrays Dim Names() As String 'use empty brackets for first declaration 'code to do something unrelated to the array goes here ReDim Names(29) As String 'resize array to store 30 items 'code to add names to the array goes here If we later ReDim the array again to hold twice as many items, its contents will be lost unless we use the keyword Preserve: ReDim Preserve Names(59) As String 'array can now hold 60 items Processing an array Suppose you have declared an array to hold 40 exam marks as follows: Dim ExamMarks(39) As Integer To store an exam mark in the 4 th subscript of the array you could write: Mark = txtexammark.text ExamMarks(3) = Mark Numeric literals, such as 3 in the above example, are not often used to identify a subscript in the array. More often you use a variable. Assuming NumberOfMarks stores how many numbers are in the array, the code below displays the array s contents: For Index = 0 To NumberOfMarks - 1 lstmarks.items.add(exammarks(index)) Next Index PROGRAM 10.1 Array to hold numbers Specification Allow the user to enter up to 5 numbers and store them in an array. Output an appropriate message if the user attempts to store a 6 th number. Allow the user to display the contents of the array at any time, and to enter a number to be searched for in the array. Display the result of this search whether the number is in the array or not. 1. Open a new project and design the form using figure 10.2. Name the buttons btnaddtoarray, btndisplay and btnfindnumber. Name the text boxes for input and searching txtnumber and txtsearchnumber respectively, name the list box for output lstnumbers, and the label to display the result of the search lbldisplaysearch. 2. Declare the array and an index into the array as global variables. These must be globals because they will be used in two event procedures. Dim Numbers(4) As Integer Dim CurrentIndex As Integer 'currently used subscript of the array 3. In the form s Load event procedure initialise CurrentIndex to -1 because, as step 4 shows, the code to add an item to the array starts by adding 1 to its value. The first time this is done we need it incremented to 0, which is the first subscript in the array. 113

Part 1 Basic Topics CurrentIndex = -1 4. In the Click event for the button to add a number to the array, you need to check if the array is full. If it is not full store the number in Numbers(CurrentIndex), i.e. in the current (free) subscript. Private Sub btnaddtoarray_click(...) Handles btnaddtoarray.click Dim Number As Integer Number = txtnumber.text If CurrentIndex = 4 Then 'array is full (has 5 numbers in it) MsgBox("The array is FULL!") 'array not full CurrentIndex = CurrentIndex + 1 'Move to next free subscript in array Numbers(CurrentIndex) = Number 'and store the number in it txtnumber.text = "" 'Clear text box ready for next number txtnumber.focus 'and place cursor in it Figure 10.2: Program 10.1 Five numbers have been stored and a number searched for 5. Because CurrentIndex also stores how many numbers there are in the array, it can be used to control a For Next loop to display the array s contents. In the Click event of the Display array button, type in: Private Sub btndisplay_click(...) Handles btndisplay.click Dim Index As Integer lstnumbers.items.clear 'Clear contents of list box or current numbers 'in array will be added to list box items For Index = 0 To CurrentIndex 'Display each used subscript in array lstnumbers.items.add(numbers(index)) Next Index 'in the list box 114

Chapter 10 Arrays 6. Run the program and check that the storage and display of numbers works. 7. To search the array for the number entered by the user the content of each array subscript must be examined, until either you find what you re looking for, or you reach the last number in the array without finding it. A Boolean value, Found, is initialised to false and switched to True if the number is found. It is used as part of the multiple condition to get out of the loop. The code used here is the standard linear search, and is one that you might find very useful in your project. Private Sub btnfindnumber_click(...) Handles btnfindnumber.click Dim Index As Integer Dim Found As Boolean Dim SearchNumber As Integer Index = 0 Found = False 'searching hasn t started yet so Found should be false SearchNumber = txtsearchnumber.text Do While (Found = False) And (Index <= CurrentIndex)'One repetition of 'the loop processes one number in the array If Numbers(Index) = SearchNumber Then Found = True 'Current subscript does not have number being searched for Index = Index + 1 'so go to the next subscript in the array Loop If Found Then 'i.e. if Found = true lbldisplaysearch.text = "This number IS in the array" lbldisplaysearch.text = "This number is NOT in the array" 8. Run the program and test the search code with a number that is present in the array and then with one that is not. Passing arrays to procedures end of Program 10.1 Some arrays can be very large. Since an actual parameter passed by value makes a copy of the contents of a parameter and passes this to the procedure, this can use up quite a lot of RAM if the array is very large. A parameter passed by reference sends only its RAM address. Whatever the size of the array, this is simply where its storage in RAM starts from and is a very small overhead. Some languages only let you send arrays by reference. Others, like Visual Basic, allow passing by value as well. Suppose you have declared an array to hold 40 people s names as follows: Dim Names(39) As String To pass Names by value to a function FindName, which returns True if a particular name is present, you might write: 115

Part 1 Basic Topics Found = FindName(SearchName, Names) 'actual parameter in function call.. Public Function FindName(ByVal WantedName As String, _ ByVal NameArray() As String) As Boolean The actual parameter, Names, has no empty brackets but the the formal parameter it is matched to, NameArray, must have them. PROGRAM 10.2 Program 10.1 with a function to search the array Specification Identical to program 10.1 but use a general procedure to search the array for the required number. In Program 10.1 several lines of code in the Click event for btnfindnumber carried out the search of the array. This task could have been put into a general procedure. If we take the procedure s job as simply reporting whether or not the number is present, and let the event procedure handle displaying the result of the search, then we can use a function with a Boolean return value. 1. Open a new project. Right-click Form1.vb in the Solution Explorer and select Delete. Confirm the deletion. Select File/Add Existing Item. Select Form1.vb from Program 10-1 and click Open. A copy of Form1 will be added to the Solution Explorer. 2. We need to change the code in the Click event for btnfindnumber (step 7 of program 10.1). Since its task is now to call the function to search for the required number and to output an appropriate message, any code which contributes to the searching itself can be removed. This means we can remove the variable Index and the loop. The function is passed the number to search for and the array. Passing the array is actually not necessary since it is a global variable and has scope in the function FindNumber, but it is included here simply to illustrate how to pass an array as a parameter. The new code should look as follows: Private Sub btnfindnumber_click(...) Handles btnfindnumber.click Dim Found As Boolean Dim SearchNumber As Integer SearchNumber = txtsearchnumber.text Found = FindNumber(SearchNumber, Numbers) 'call the function If Found Then 'i.e. if Found = true lbldisplaysearch.text = "This number IS in the array" lbldisplaysearch.text = "This number is NOT in the array" The return value from the function FindNumber is stored in the Boolean Found and this is used to output the message. 3. Write the function s declaration below the code in step 2. Public Function FindNumber(ByVal WantedNumber As Integer, _ ByVal NumberArray() As Integer) As Boolean 116

Chapter 10 Arrays Both formal parameters can be passed by value because we do not need to change their contents. Since the function must return whether or not the number is present, the return value is declared, outside the parameter brackets, as Boolean. 4. Complete the code to carry out the search and return a true or false value as shown below. The search code is the same as that in program 10.1, except that the formal parameter, WantedNumber, is used. Dim Index As Integer Dim Found As Boolean Found = False Index = 0 Do While (Found = False) And (Index <= CurrentIndex) If NumberArray(Index) = WantedNumber Then Found = True Index = Index + 1 Loop If Found Then Return True 'function s return value is True or False Return False End Function 5. Run the program and check that the function works when the Find number button is clicked. Two-dimensional arrays end of Program 10.2 All the arrays so far have been one-dimensional. Suppose you wished to store a firm s quarterly sales figures for the decade 1990-1999. This requires 4 (quarters) x 10 (years) = 40 pieces of data. You could declare a two-dimensional array to hold this data as follows: Dim SalesFigures(9, 3) As Decimal '10 rows (years), 4 columns (quarters) After running the following code SalesFigures(0, 2) = 56800 SalesFigures(8, 3) = 96400 the array would look like the matrix shown in figure 10.3. The years are the rows and the quarters the columns. You can have arrays with more than two dimensions, but it s unlikely you would ever need to use one. Two-dimensional arrays are useful for storing data for some mathematical problems, but in business type problems they are less useful because all their data items must be of the same data type. An array of records (covered in the next chapter) is often a more convenient data structure. 117

Part 1 Basic Topics (1990) 0 0 1 2 3 56800 SalesFigures(0, 2) (1991) 1 (1998) 8 96400 SalesFigures(8, 3) (1999) 9 Figure 10.3: A two-dimensional array Control arrays A control array is a group of controls which are all of the same type. You can have a control array of text boxes, of buttons and so on. You declare a control array as you would an ordinary array. For example to have an array of 3 text boxes, first declare the array and then populate it with the text boxes: Dim TextBoxArray(2) As TextBox txttextboxarray(0) = txtnumber1 txttextboxarray(1) = txtnumber2 txttextboxarray(2) = txtnumber3 If you then wished to display the numbers 10, 20 and 30 in these text boxes you would write: For Index = 1 To 3 TextBoxArray(Index - 1).Text = Index * 10 Next Index PROGRAM 10.3 A control array Specification Represent the 4 tennis courts owned by a small tennis club by numbered labels on a form. They should be coloured green when the program starts. The user should enter a number from 1 to 4 in a text box, and then click a button to change the colour of the corresponding tennis court to red to show that it is in use. Figure 10.4 shows that court 3 is in use. 1. Open a new project. Build the form using figure 10.4. Name the four tennis court labels lblcourt1 to lblcourt4 and set their Text property to 1 to 4 as appropriate. Set their BackColor property to Green by clicking the small button in this property, selecting the Custom tab and then selecting any green colour. Name the text box txtnumber and the button btnok. 118

Chapter 10 Arrays Figure 10.4: Program 10.3 Tennis court 3 is in use 2. The control array will consist of the four tennis court labels. Declare it as a form variable: Dim lblcourts(3) As Label 3. In the form s Load event we need to assign each of the tennis court labels to the control array. lblcourts(0) = lblcourt1 lblcourts(1) = lblcourt2 lblcourts(2) = lblcourt3 lblcourts(3) = lblcourt4 4. In the Click event for the OK button declare the local variables and store the court number. Private Sub btnok_click(...) Handles btnok.click Dim CourtNumber As String Dim Index As Short CourtNumber = txtnumber.text 5. We then need to loop through the control array to find the relevant label and colour it red: For Index = 0 To 3 If lblcourts(index).text = CourtNumber Then lblcourts(index).backcolor = Color.Red Next Index 6. Run the program. Enter a number from 1 to 4 in the text box and click the button. The corresponding court will be coloured red. Shared event handler end of Program 10.3 The code templates provided for every event procedure we have used so far include the keyword Handles. A common one has been a button s Click event: 119