Sie sind auf Seite 1von 12

ARRAYS

Arrays

Group of related variables The group is referred to as array of variables or simply, an array Can be used just like any variables: assign a value, use in calculations, display content, etc.

One-Dimensional Arrays

Each variable has the same name and the same type Array names follow the same conventions that apply to other variable names To refer to a variable in a one-dimensional array, a unique number is used, also called a subscript

Arrays
Name of array (Note that all elements of this array have the same name. numberArray)
numberArray(0 -45 ) numberArray(1 6 ) numberArray(2 0 ) numberArray(3 72 ) numberArray(4 1543 ) numberArray(5 -89 ) numberArray(6 0 )

Position number (index or subscript) of the element within array numberArray

Arrays

Values stored in arrays can be employed in various calculations and applications Examples:
Determine

the sum of the values contained in the first three elements of numberArray Divide the value of the seventh element of numberArray by 2 and assign the result to variable result

Common Programming Error

It is important to note the difference between the seventh element of the array and the array element seven This confusion is a common source of off-byone errors

Declaring a One-Dimensional Array

The following statement declares an array: Dim arrayName(highestSubscript) As dataType Dim arrayName() As dataType = {initialValues} Assigning initial values to an array is often referred to as populating the array

Declaring a One-Dimensional Array

Example 1:

Dim strNames(3) As String

Example 2:

Dim scores(45) As Integer

Example 3:

Dim places() As String = {Manila, Quezon City, Makati, Taguig}

Example 4:

Dim payments() As Double = {150, 89.50, 56.75, 998.25, 546.90,

Determining the Number of Elements and the Highest Subscript

To determine the length of the array, we use the following expression: Name of array.Length e.g. numberArray.Length To get the last element in the array, we use the expression: Name of array.GetUpperBound(0) e.g. numberArray.GetUpperBound(0)

Storing data in a One-Dimensional Array

Example 1:

places(0) = Pasig

Example 2:

For intX As Integer = 1 To 6 intNumbers(intX 1) = intX ^ 2 Next intX

Example 3:

payments(2) = payments(2) * .25

Examples Using Arrays

Create an array of 10 Integer elements. The program should display the array elements and their values in a label.

Examples Using Arrays

Twenty students were asked to rate on a scale of 1 to 10 the quality of the food in the cafeteria with 1 being the lowest and 10 being the highest. Place the 20 integers in an integer array and determine the frequency of each rating.

Das könnte Ihnen auch gefallen