You are on page 1of 23

CST8116 Intro. to Comp. Prog.

Week 11 Lesson 01
Problem Solving with Arrays
Week 11 Lesson 01
Problem Solving with Arrays
• What is an Array?
• Array Declaration
• Array subscript (index), element, size, populating
• Remaining within Array Bounds
• How Arrays Occupy Computer Memory
• Declaring and Populating Array on same line
• Characteristics of Arrays
• Problem Solving with an Array (Example)
• Arrays and Constants
• Searching an Array: Linear Search
• What is a Parallel Array?
• Why should we not use Parallel Array in Java?
• Using for Loop to Process an Array
2
Welcome
This slide set provides an introduction to arrays, as used in the context of
computer programmer.
Much of the content for this slide set follows Chapter 6 of Joyce Farrell's book [1].

3
What is an Array?
• An array is a collection of values having the same data-type stored in the
computers memory in a linear, contiguous, manner.
• Aspects of real-life can be represented in a computer program as an array.
• Examples
• The letters of the alphabet to make an index system
• The prices for each of the items for sale in a store
• The amount of gasoline used to refuel a car each month
• And more.

4
Array Declaration
• An array declaration looks like:
num prices[3]
• There is a data-type: num (for numeric data)
• The variable-name of the array: prices
• The size of the array within square brackets: [3]
• By convention arrays are named with a plural name
prices, costs, indexes, names, etc.
• Joyce Farrell [1] introduces arrays with the size after the variable name,
however Java programming conventions place the brackets adjacent to the data
types.[2] (Note that declaration and instantiation can be on separate lines)
double[ ] prices = new double[3];

5
Array subscript (index), element, size, populating
• Each storage location in the array is referred to as an element.
• Each element in the array is accessed using a subscript (also called an index)
using square brackets as well.
• Populating an array means initializing the elements with data.
num prices[3]
prices[0] = 33.40
prices[1] = 45.32
prices[2] = 22.45
• The lowest index for an array is zero: prices[0]
• The maximum index for an array is array size minus one: 3 minus 1 is 2.

6
Remaining within Array Bounds
• Array Bounds:
• Lower bound, the lowest index value, zero i.e. [0]
• Upper bound, the highest index value, size – 1, i.e. [size-1]
• Using an index value that is outside of the Array Bounds will cause problems.
• Best case, your program experiences a run time error and crashes.
• Worse case, your program corrupts computer memory that is not part of
your program, causing other programs or the operating system to crash.
• Java Arrays enforce Array Bounds, with a run-time exception causing a crash.[2]
• It is important to enforce array bounds in programming, this is a security exploit
used by hackers to corrupt memory and run viruses. See Computing and
Society 7.1 Computer Viruses pp 229 to 230 in Horstmann’s book. [2]

7
How Arrays Occupy Computer Memory
• The memory in the computer is organized as a sequence of 1-byte blocks of 8-
bits each. We can represent this as a sequence of blocks.

• Each byte in the computer, has a unique memory address


• We specify the data type for the array, and each element in the array will occupy
the amount of bytes for the data type. E.g. In Java an int is a 32-bit numeric
type, it occupies 4-bytes of memory.
• Each element of an array of int type is 4-bytes of memory.
• Each element of an array is placed immediately after the other in memory in a
contiguous manner.

8
How Arrays Occupy Computer Memory
• num numbers[3]
*This is 3 x 4-bytes, so 12-bytes of memory (3 x 32-bit is 96 bits).

• Using the name of the array, and the subscript, and the size of the data-type, the
system performs calculations internally to jump to the correct memory location
and read/write a value. *In the diagram above, num is assumed to be 4-bytes.
Read from a single array element: int value = numbers[0]
Write to a single array element: numbers[0] = 33

9
Declaring and Populating Array on same line
• Some programming languages permit an array to be populated with starting
values, on the same line the array is declared on, separating literal values with
commas.
num numbers[5] = 3.3, 4.4, 2.45, 6.0, 4.0
• The left-most value will be placed into the element indexed with 0
• In the diagram below, each element (regardless of the number of bytes) is
represented by a single box. The values from the line of code above are shown.

10
Characteristics of Arrays
This slide is directly quoted from [1] page 230.
• An array is a list of data items in contiguous memory locations.[1]
• Each data item in an array is an element.
• Each array element is the same data type; by default, this means that each
element is the same size.
• Each element is differentiated from the others by a subscript, which is a whole
number.
• Usable subscripts for an array range from 0 to one less than the number of
elements in an array.
• Each array element can be used in the same way as a single item of the same
data type.

11
Problem Solving with an Array (Example)[1]
• A special case of using an array, is to replace a complex decision structure [1]
• A school needs to count the number of each letter grade assigned to students at
the end of a course, i.e. count how many A, B, C, D, or F grades were awarded.
• We can create variables to store the counts, with a loop for data entry, and a
selection structure to increase each count as needed.
• Pseudocode continues next slide
start
declarations
countA
countB
countC
countD
countF
12
Problem Solving with an Array (Example)[1]
while shouldContinue = “Y”
input grade
if grade = “A”
countA = countA + 1
else if grade = “B”
countB = countB + 1
else if grade = “C”
countC = countC + 1
else if grade = “D”
countD = countD + 1
else
countF = countF + 1
endif
input shouldContinue
endwhile

13
Problem Solving with an Array (Example)[1]
• Replacing the if structure as well as the counting variables with an Array.
• We would ask the user to enter 4 for A, 3 for B, 2 for C, 1 for D, and 0 for F
num grades[5]
while shouldContinue = “Y”
input numericGrade
grades[numericGrade] = grades[numericGrade] + 1
input shouldContinue
endwhile
output "The number of A grades is: " + grades[4]
• numericGrade will be one of the array indexes, causing the value at that index to
increase by 1.
• i.e. if the user enters 4, then it is the same as grades[4] = grades[4] + 1

14
Arrays and Constants
• Using a constant for the size of the array is a good practice, it makes it easier to
change the array size later if needed when maintaining the software, this also
removes Magic Numbers from the program

num ARRAY_SIZE = 5
num grades[ARRAY_SIZE]

15
Searching an Array: Linear Search
• Loops are often used with arrays, the loop control variable also acts as the
index value, so each element in the array can be accessed in sequence.
• Searching an Array is a common task in programming, the most basic way to do
so it a Linear Search.
• Understanding the problem:
Use a loop, with a loop control variable, and retrieve the contents of each
element in the array one at a time to check if it matches a value I am looking for.
If a match is found, report the index the match occurred at, otherwise report that
a match was not found. (A common, match-not-found value is -1, by
programmer convention.)

16
Searching an Array: Linear Search
start findItem(num item)
declarations declarations
num SIZE = 3 num index = 0
num numbers[SIZE] = 3.3, 4.4, 2.45 num foundIndex = -1
num searchValue while index < SIZE AND foundIndex < 0
num foundAtIndex if numbers[index] = item then
output "Enter search number" foundIndex = index
intput searchValue else
foundAtIndex = findItem(searchValue) index = index + 1
if foundAtIndex > -1 then endif
output "found" endwhile
else return foundIndex
output "not found"
endif
stop

17
Searching an Array: Linear Search

18
What is a Parallel Array?[1]
• Any given array only stores one type of data.
• If we need to store pieces of data related to a record, for example a customer
name and id number we can store the needed values in two arrays
• One array of num type for the ids
• One array of string type for the names
• We then need to keep the array indexes synchronized when manipulating the
arrays to read or write data.

19
Why should we not use Parallel Array in Java?[2]
• Parallel arrays should be avoided in Java.
• Create a class, then an array of reference type instead.
(More about reference type arrays in Java in a future lecture)
• If the record-keeping expands to add more data items for each record
(commonly called fields) a great deal of maintenance work in adding more
parallel arrays and ensuring the correct index is needed.
• An object can have a private class-level variable added, a get/set and or an
overloaded constructor added if needed, and keep using the same single array.

20
Using for Loop to Process an Array
• A for loop is a natural way to sequentially access each element in the array, a
process known as iterating over the array.

num upperBound = SIZE - 1


for index = 0 to upperBound step 1
arrayName[index] // do the things as needed
endfor

21
Conclusion
In this lesson we reviewed:
• What is an Array?
• Array Declaration
• Array subscript (index), element, size, populating
• Remaining within Array Bounds
• How Arrays Occupy Computer Memory
• Declaring and Populating Array on same line
• Characteristics of Arrays
• Problem Solving with an Array (Example)
• Arrays and Constants
• Searching an Array: Linear Search
• What is a Parallel Array?
• Why should we not use Parallel Array in Java?
• Using for Loop to Process an Array
22
References
[1] Joyce Farrell. 2018. Programming Logic & Design Comprehensive. 9th Ed.
Cengage Learning. Chapter 6 pp. 227 to 271 (All Sections)
[2] Cay Horstmann. 2019. Big Java Early Objects. 7th Ed. Wiley. Chapter 7 pp. 221
to 248. (Only up to, but excluding section 7.6 onwards)

23

You might also like