Title: Array Basics
1TOPIC 8
Arrays
- Array Basics
- Arrays and Methods
- Programming with Arrays
2 Handling seven temperature readings class
TemperatureReadings BufferedReader keyboard
new BufferedReader (new InputStreamReader(System
.in)) public static void main(String
args) double temperature1,
temperature2, temperature3,temperatur
e4, temperature5,temperature6,temperature7
// more code will go here
3 Code to enter all seven temperatures Getting
one temperature is easy
System.out.println("max temperature for day 1
?") temperature1 Double.parseDouble (keyboa
rd.readLine( ))
4 Try using a loop?
for (int i1 ilt7 i) System.out.println("
max temperature for day " i) temperature1
Double.parseDouble (keyboard.readLine( ))
5Arrays
- An array is an ordered list of values
0 1 2 3 4 5 6 7 8
9
An array of size N is indexed from zero to N-1
This array holds 10 values that are indexed from
0 to 9
6Arrays
- A particular value in an array is referenced
using the array name followed by the index in
brackets - For example, the expression
- scores2
- refers to the value 94 (the 3rd value in the
array) - That expression represents a place to store a
single integer and can be used wherever an
integer variable can be used
7- CREATING AN ARRAY
- (Arrays are used to hold a collection of items
all of the same type. ) - Array creation is a two stage process
- 1. Declare an array.
- ArrayType arrayName
- 2. Create memory to store the array.
- arrayName new ArrayType sizeOfArray
- Examples80-element character array char
symbol new char80100-element array of
doubles double reading new double100
8 CREATING AN ARRAY OF TEMPERATURES Since
each temperature is of type double an array of
temperature readings is declared as follows
double temperature
Since there will be seven temperature readings,
memory is reserved for this array ass follows
temperature new double 7
9The effect on computer memory of declaring an
array of values of type 'double'
10 NAMING OF ARRAY ELEMENTS
- Each element in an array shares the same name as
the array. - The individual elements are then uniquely
identified by an additional index value. - Array indices start from 0 (and not from 1).
- This index value is always enclosed in square
brackets - first temperature temperature0
- second temperature temperature1
11Some array terminology
Array name
- temperaturen 2
- temperaturen 2
- temperaturen 2
- temperaturen 2 32
Index - also called a subscript - must be an
int, - or an expression that evaluates to an
int
Indexed variable - also called an element or
subscripted variable
Value of the indexed variable - also called an
element of the array
Note that "element" may refer to either a single
indexed variable in the array or the value of a
single indexed variable.
12 ACCESSING ARRAY ELEMENTS
temperature0 Double.parseDouble (keyboard.
readLine( )) System.out.println(temperature5)
System.out.println ("temperature for day 1 is
temperature0) temperature4
temperature4 2 if (temperature2 gt
18) System.out.println("it was hot today")
13USING A LOOP TO ENTER VALUES INTO AN ARRAY
for(int i 0 i lt 7 i)
System.out.println("max temperature for day
(i1)) temperaturei
Double.parseDouble (keyboard.readLine( ))
14 THE 'length' ATTRIBUTE
- for (int i 0 i lt temperature.length, i)
-
- // code for loop goes here
-
- Array length is specified by the number in
brackets when it is declared. - Determines amount of memory allocated for array
elements (values). - Determines the maximum number of elements the
array can hold. - Storage is allocated whether or not the elements
are assigned values.
15EXAMPLEArray stores 7 temperatures and displays
average temperature whether each temperature is
below, above or same as the average temperature.
- public class ArrayOfTemperatures
-
- static BufferedReader keyboard
- new BufferedReader(new InputStreamReader(Syst
em.in)) -
- public static void main(String args)
-
- double temperature new double7
- int index
- double sum 0.0, average
- System.out.println(Enter 7 temperature
readings) - Â
- for (index 0 index lt 7 index)
-
- temperatureindex
- Double.parseDouble(keyboard.readLine())
- sum sum temperatureindex
-
16- average sum / 7
- System.out.println(The average temperature is
average) - Â
- System.out.println(The temperatures are )
- for (index 0 index lt 7 index)
-
- if (temperatureindex lt average)
- System.out.println(temperatureindex below
average) - else
- if (temperatureindex gt average)
- System.out.println(temperatureindex
above average) - else
- System.out.println(temperatureindex is
the average) -
-
-
17 INITIALIZING AN ARRAY (declaration)
An initializer list can be used to instantiate
and fill an array in one step The values are
delimited by braces and separated by
commas Examples double temperature 9,
11.5, 11, 8.5,
7, 9, 8.5 char letterGrades 'A', 'B',
'C', 'D', F'
18Subscript range
- Array subscripts use zero-numbering
- the first element has subscript 0
- the second element has subscript 1
- etc. - the nth element has subscript n-1
- the last element has subscript length-1
- For example
- int scores 97, 86, 92, 71
19Subscript out of range error
- Using a subscript larger than length-1 causes a
run time (not a compiler) error - an ArrayOutOfBoundsException is thrown
- you do not need to catch it or declare it in a
throws-clause - you need to fix the problem and recompile your
code -
- Other programming languages, e.g. C and C, do
not even cause a run time error! - one of the most dangerous characteristics of
these languages is that they allow out of bounds
array indexes.
20Good programming practice
- Using singular rather than plural names for
arrays improves readability - although the array contains many elements the
most common use of the name will be with a
subscript, which references a single value - Do not count on default initial values for array
elements - explicitly initialize elements in the declaration
or in a loop
21Array size
- FIXED-SIZE ARRAY DECLARATION
- int number new int100
- Problems??
- Dont always know array size at compile time.
22Some operations on arrays
- Initialize
- Input data
- Output stored data
- Find largest/smallest/sum/average of elements
23How To Specify Array Size During Program Execution
int arraySize // Declare array System
.out.println("Enter size of the array ")
arraySize Integer.parseInt(keyboard.readLine()
) int list new intarraySize //
Create array
24Code to Initialize Array to Specific Value (10.00)
for(index 0 index lt sale.length index)
saleindex 10.00
25Code to Read Data into Array
for(index 0 index lt sale.length index)
saleindex Integer.parseInt(keyboard.readLine()
)
26Code to Print Array
for(index 0 index lt sale.length index)
System.out.print(saleindex " ")
27Code to Find Sum Average of Array
sum 0 for(index 0 index lt sale.length
index) sum sum saleindex if(sale.l
ength ! 0) average sum /
sale.length else average 0.0
28Determining Largest Element in Array
maxIndex 0 for(index 1 index lt sale.length
index) if(salemaxIndex lt saleindex)
maxIndex index largestSale
salemaxIndex
29Determining Largest Element in Array