Transcript Arrays

Arrays
Arrays
• An array is a variable that holds a
collection of related data values.
• Each of the values in an array is called
an element.
• Each element in the array is identified by
an integer value called its index, which
indicates the position of the element in
the array.
2
Array
• Multiple instances of the same type of item
• Instances in the array are called elements
• Each element has a subscript or index
Name
Bill
Names()
0
1
2
3
Bill
Jane
Joe
Sally
3
Arrays
• Most modern programming languages
implement zero-based arrays, meaning
that array index values begin with 0
• The array length is the number of
elements in the array.
• The upper bound of an array is the index
of the last element.
4
Accessing Individual Elements
of an Array
• To access individual array elements, you
specify the array name and follow it with
an index expression enclosed in
parentheses.
• If you attempt to reference an array with an
index value greater than the upper bound of
the array, the result will be an out-ofbounds error.
5
Array Reference
Scores(0)
Scores(1)
Scores(2)
Scores(3)
Scores(4)
Scores(5)
Scores(6)
Scores(7)
Scores(8)
6
When to Use Arrays
• Arrays are useful…
– when you are storing or processing large
amounts of related data
– when information must be stored and
processed twice
– when you want to store multiple entries of
related information
7
File Input
• Rather than enter a
large number of
values (or even a
small number) every
time the program is
ran, you can get the
values from a data
file.
• Supply the full path to
the file.
8
Above Average Problem
(Mutual Funds)
• The Problem
– Jim is a financial analyst with many large
investment clients. Each year Jim identifies ten
different mutual funds that he shares with his
clients for investing. At the end of each year he
keeps the funds that performed better than the
ten-fund average and replaces the others with
new funds.
9
Funds Problem Statement
• Input
Funds
– 10 fund performance values
• Process
– Sum the 10 fund performance values
– Divide the Sum by 10 to get the average
– For each fund determine if is above the average
• Output
– Average of the 10 funds
– Funds that are above the average
1.078
1
1.13
2
1.21
3
0.98
4
1.37
5
0.95
6
1.01
7
0.87
8
1.21
9
1.06
10
0.99
10
Parallel Arrays
(Girl Scout Cookies)
• The Problem
– Every spring you look forward to buying a box
of Caramel deLites Girl Scout cookies from
your niece, Belinda. Her troop gives an award
to the girl who sells the most boxes of cookies
each year. They are looking to develop a
software solution to assist in determining the
annual award winner.
11
Analysis and Design
• Parallel arrays are two or more arrays
whose elements are related by their position
in the arrays.
12
Analysis and Design (cont.)
13