COP1000 1
Processing Arrays
Lesson 8
McManus
COP1000 2
Overview• One-Dimensional Arrays
– Entering Data into an Array– Printing an Array– Accumulating the elements of an Array
• Two-Dimensional Arrays– Loading a Two-Dimensional Array– Printing a Two-Dimensional Array– Accumulating the Rows and Columns of a Two-
Dimensional Array
McManus
COP1000 3
Overview cont. • Multidimensional Arrays• Table Look-Up Technique
– Sequential Search– Binary Search
• The Pointer Technique– Frequency Distribution– Cross Tabulation
McManus
COP1000 4
Arrays• A consecutive group of memory locations
that all have the same name and the same data type.
• Are the simplest structured type.– Component access is by a position number (an
index) that indicates the component’s position within the collection.
• Examples MyArray(3)MyArray(n)
McManus
COP1000 5
Simple Arrays• Are declared at compile time.
– Compiler reserves the appropriate amount of contiguous memory to hold the array.
• Occupy storage in memory– System must have enough memory– Memory may be reserved for more than one
array in one statement, but not recommended.– Examples:
• Dim (99) As Integer in VB declares an array of 100 Integer elements
• Dim s(14) As String in VB declares an array of 15 String elements
• Int age[12]; in C++ declares an array of 12 Integer elementsMcManus
COP1000 6
Array Initialization
McManus
Private Sub cmdPrint_Click()Dim anarray(9) As Integer ‘10 ElementsDim x As Integer ‘Used as Loop CounterlblDisplay.Text = "Index" & Space(3) & _
"Value" ‘HeadingFor x = 0 To anarray.GetUpperbound(0) _
Step 1 anarray(x) = 5
lblDisplay.Text = x & Space(7)& anarray(x)Next x
End Sub
VB Code
What will it display?
COP1000 7
A Different Method of Initialization
McManus
Private Sub cmdPrint_Click()Dim anarray(9) As Integer ‘10 ElementsDim x As Integer ‘Used as Loop CounterlblDisplay.Text = "Index" & Space(3) & _
"Value" ‘HeadingFor x = 0 To anarray.GetUpperbound(0) _
Step 1 anarray(x) = x
lblDisplay.Text = x & Space(7)& anarray(x)Next x
End Sub
VB Code
What will it display?
COP1000 8
Array Initialization– In VB, by default, the first array index is
initialized to 0 and VB won’t allow you to change the default.
– However, other languages, like Pascal, will allow the programmer to initialize the array to something other than zero, but you have to do it...• Note…not all languages have this facility…• In other languages, you have to initialize the
array.McManus
COP1000 9
1 2 3 4 5 6 7a b c c d e f
Array Type Declarationtype
CharArray = array [1..7] of Char;Allocate storage for the array
varLetterArray : CharArray;
LetterArray
LetterArray[3] = ‘c’
the element in Position 3 is "c"McManus
Pascal Code
Index
Element
COP1000 10
Accessing Array ElementsTo access the array called numbers, call
the array by name and include in () the index (or location) of the value to be accessed.
numbers(2) 23; numbers(4) 32Note: the second element in the array
is not 23.Source of off-by-one errors
Print numbers(2) + numbers(3) will print 51
McManus
10 15 23 28 32 45 47
0 1 2 3 4 5 6An array calledNumbers
Index
COP1000 11
Some ExamplesNumbers( 2 ) + Numbers( 3 )
5 + 7 = 12 Numbers( 2 + 3 ) value stored in 5 is
6Numbers( 2 ) + 3 valued stored in 2 is
5 5 + 3 = 8Numbers( 5 - 3 + 2 ) value stored in 4 is
3Numbers( 2 * 3 ) value stored in 6 is
4Numbers( 9 + 2 ) generates a syntax
errorMcManus
Index 0 1 2 3 4 5 6 7 8 9 10Value 10 2 5 7 3 6 4 1 3 9 1
COP1000 12
How Random Access Works
• The computer calculates the addresses of an array for you.
McManus
Index_Location = Base + (Index * Element_Length)Index_Location = 1000 + ( 3 * 2 )
Index_Location(3) = 1006 which is the Address for the element stored at
Index 3.
Index
Elements1000Base2 bytes 2 bytes 2 bytes 2 bytes 2 bytes 2 bytes 2 bytes
0 1 2 3 4 5 610 15 23 28 32 45 47
Not On the Test!
COP1000 13
Storing Data in an Array• Must be read into an array one
element at a time.• Must be displayed one element at a
time.for Index := 1 to MaxItems do
Read (DataArray[Index]);
for Index := 1 to MaxItems doWriteLn (Index :4, DataArray[Index] :8:1);
McManus
Pascal Code
COP1000 14
One-Dimensional Arrays• The simplest Array Structure
Ex. Array - Age Variable Name
AGE (1) = 32AGE (2) = 54AGE (3) = 25AGE (4) = 36AGE (5) = 45AGE (6) = 20AGE (7) = 28AGE (8) = 50
McManus
The Number in the Parentheses refers to theBox number in the Array, the Element Number
Index
1 2 3 4 5 6 7 832 54 25 36 45 20 28 50
Elements
COP1000 15
Accessing Arrays• Individual array elements and entire arrays
can be passed as parameters.• Arrays can also be copied from one array
to another.const MaxSize = 100;type IndexRange = 1..MaxSize; TestArray = array [IndexRange] of Real;var XArray, YArray : TestArray; {declares both as arrays}
XArray := YArray {the code: copies YArray to XArray}
McManus
Both arrays must beof the same data type.
Pascal Code
COP1000 16
Entering Data into an Array
• To Load an Array, use a Loop– If you know the number of elements,
then use the automatic-counter loop (For loop)
– If you don’t know the number of elements, then use an indicator code with the Repeat/Until or the While/While-end loop
McManus
COP1000 17
Automatic-Counter Loop
McManus
Algorithm For Index = 1 To N Step 1 AnArray(Index) = X Next Index
Index = CounterN = Number of elements in AnArrayAnArray(Index) = Element Index in ArrayX = data entered into AnArray(Index)
AnArray(Index) = X
Index <= N
Index = Index + 1
Index = 1
False
True
FlowchartPseudocode
COP1000 18
Repeat/Until LoopUsing Definite Looping
McManus
AlgorithmIndex = 0Repeat
Index = Index + 1AnArray(Index) = X
Until Index > 10
X = data entered into AnArray(Index)
Index = 0
Index = Index + 1
AnArray(Index) = X
UntilIndex > 10
True
False
Pseudocode
Flowchart
COP1000 19
While/While-End LoopUsing Indefinite Looping
McManus
AlgorithmIndex = 1AnArray(Index) = ReadvalueWhile AnArray(Index) <>
SentinelAnArray(Index) = Readvalue
End While
Sentinel = end test valueReadvalue = value being read in
from user
Index= 1
AnArray(Index) = Readvalue
True
False
AnArray(Index) = Readvalue
AnArray(Index) <>
Sentinel
FlowchartPseudocode
COP1000 20
Printing an Array
McManus
AlgorithmFor Index= 1 To N Step 1
Print AnArray(Index)Next Index
N = Total number of elements
AnArray(Index) = ith element of Array
Print AnArray(Index)
Index <= N
Index = Index + 1
Index = 1
False
True
implicit
Implicit Step
Note: Not all languages begin with 1 as the default first element.Some, like VB, begin with 0
FlowchartPseudocode
COP1000 21
Two-Dimensional Arrays• A two-dimensional array is a block of
memory locations associated with a single memory variable name and designated by row and column numbers
• Each element is written as A (Row#,Column#) – The row number is always first, and the column
number second– Note: This is different than in Excel
McManus
COP1000 22
Two-Dimensional Arrays• For a two-dimensional array,
information is stored in rows and columns.– Requires two indexes:
• The first, by convention, represents the row• The second represents the column.• Cannot use the same index for both.
– Ex. mArray (x, y) or mArray(row, col) In
VBint TwoDimArray[r],[c] In C+
+McManus
COP1000 23
Two-Dimensional Array
McManus
Rows
Columns1st
Element
Subscripts (indexes)
0,3
1,1 1,3
0,1 0,2
1,21,0
0,0
1843959315612
78
COP1000 24
Loading a Two-Dimensional Array
• You load a Two-dimensional Array with nested loops—one loop for each dimension– When the data is loaded row by row, the
outer loop represents the row, and the inner loop represents the column
– This order of the loops allows the row number to stay constant while the column number varies
McManus
COP1000 25
Loading a Two-Dimensional Array
AlgorithmFor R = 0 To 4 Step 1 Sum = Sum + Sales(R,C) For C = 0 To 4 Step 1 Total = Total + Sales(R,C) Next CNext R
McManus
FlowchartEnter
Exit
C = 0 to 4
Sum = Sum + Sales(R,C)
Total = Total + Sales(R,C)C
R = 0 to 4
R
0,3
1,1 1,3
0,1 0,2
1,21,0
0,0876
43219
2,3
3,1 3,3
2,1 2,2
3,23,0
2,0181716
1413121119
4,1 4,34,24,0 232221 24
0,4
1,4
510
2,4
3,4
1520
4,425
rows
columns
An array called Sales
Pseudocode
COP1000 26
Multidimensional Arrays• Arrays with 3 or more dimensions
– can facilitate an understanding of the data,
– improve the readability of algorithms, and
– facilitate processing since the data can be processed through the use of three or more nested loops.
McManus
COP1000 27
Multidimensional Arrays• The recommended variable names
for the indexes for a 3-dimensional array would be – R for Row– C for Column – D for Depth– V for Volume
• These arrays are processed much like 2-dimensional arrays
McManus
For each additional dimension, an additional loop is used to manipulate the dimension
COP1000 28
Arrays and Lists
How do they differ?
McManus
COP1000 29
Arrays vs. ListsArrays• Arrays use Random
Access• Arrays use Indices
to access elements• Arrays are declared
at Compile Time• Array elements are
stored in contiguous memory
Lists• Lists use Sequential
Access• Lists use Pointers• Lists are declared at
Run Time• List elements are
stored in any available location
McManus
Know This!
COP1000 30
Attempt the end, and never stand to doubt; Nothing’s so hard, but search will find it out.
Robert Herrick
McManus
COP1000 31
Table Look-up Technique• A common application for arrays is
using a value to look up another value in a table
• Two (of many) methods for looking up values in an array or table – The Sequential search method– The Binary search method
McManus
COP1000 32
Sequential Search • This method is used when you don’t know
the element number, but you do know the value of the element
• The methodology is simple. – Given the search value of the element you
want to find, element one is tested to see if it matches the search variable. • If it does, the flow of the program drops out of the
loop. • If it doesn’t, the element number is incremented and
loops back to test again
McManus
COP1000 33
Binary Search• This is a High speed search• This search technique involves comparing
the mid-element of all or part of the array. – If it compares then it drops you out of the loop.– If it does not, the program checks to see if the
value is lower or higher than the middle value.
McManus
[First] [Middle] [Last]
Item
F M-1 M M+1 L
COP1000 34
Binary Search cont.– The boundaries are then reset to select a new
section of the array. – The program continues to divide the array in
half until the desired element is found• A 1,000 element array would take
less than 10 comparisons
McManus
COP1000 35
The Pointer Technique• Method using arrays to specify the
value of an element in one array as the element number in another array– The value of the element in the first
array points to element in the second array
• Techniques– Frequency Distribution and – Cross-Tabulation
McManus
COP1000 36
Frequency Distribution • A tally of one type of value in an
array– Example: how many students in a
school are in each class or how many of a company’s customers live in each zip code area
• The result of a frequency distribution is a one dimensional array that contains the value for each element number
McManus
COP1000 37
Frequency Distribution Example
McManus
Index Values(Age Groups)
1 1-20
2 21-30
3 31-40
4 41-50
5 51-60
Index Frequency(# in each
Group)1 3
2 5
3 4
4 2
5 1
COP1000 38
Cross-Tabulation• This uses the pointer technique for
calculating statistics from a questionnaire– Example: How many students are in each
major and each class• The result of this cross-tabulation is a two-
dimensional array containing the tally for the combination of the majors and classes– The majors would be the rows and the classes
would be the columns
McManus
COP1000 39
Cross Tabulation Example
Yes(1)
No(2)
Females(1) 32 25
Males(2) 51 42
McManus
COP1000 40
Next?
McManus