Array Basics - PowerPoint PPT Presentation

1 / 29
About This Presentation
Title:

Array Basics

Description:

Code to enter all seven temperatures. Getting one ... Since there will be seven temperature readings, memory is reserved for this array ass follows: ... – PowerPoint PPT presentation

Number of Views:62
Avg rating:3.0/5.0
Slides: 30
Provided by: LewRa5
Category:

less

Transcript and Presenter's Notes

Title: Array Basics


1
TOPIC 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( ))
5
Arrays
  • 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
6
Arrays
  • 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
9
The 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

11
Some 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")
13
USING 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.

15
EXAMPLEArray 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'
18
Subscript 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

19
Subscript 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.

20
Good 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

21
Array size
  • FIXED-SIZE ARRAY DECLARATION
  • int number new int100
  • Problems??
  • Dont always know array size at compile time.

22
Some operations on arrays
  • Initialize
  • Input data
  • Output stored data
  • Find largest/smallest/sum/average of elements

23
How 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
24
Code to Initialize Array to Specific Value (10.00)
for(index 0 index lt sale.length index)
saleindex 10.00
25
Code to Read Data into Array
for(index 0 index lt sale.length index)
saleindex Integer.parseInt(keyboard.readLine()
)
26
Code to Print Array
for(index 0 index lt sale.length index)
System.out.print(saleindex " ")
27
Code 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
28
Determining Largest Element in Array
maxIndex 0 for(index 1 index lt sale.length
index) if(salemaxIndex lt saleindex)
maxIndex index largestSale
salemaxIndex
29
Determining Largest Element in Array
Write a Comment
User Comments (0)
About PowerShow.com