arrays 1 topic 8 l array basics l arrays and methods l programming with arrays arrays

29
ARRAYS TOPIC 8 Array Basics Arrays and Methods Programming with Arrays Arrays

Upload: ashley-mills

Post on 13-Jan-2016

245 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: ARRAYS 1 TOPIC 8 l Array Basics l Arrays and Methods l Programming with Arrays Arrays

ARRAYS 1

TOPIC 8

Array Basics Arrays and Methods Programming with Arrays

Arrays

Page 2: ARRAYS 1 TOPIC 8 l Array Basics l Arrays and Methods l Programming with Arrays Arrays

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,temperature4,

temperature5,temperature6,temperature7;

// more code will go here

}

}

Page 3: ARRAYS 1 TOPIC 8 l Array Basics l Arrays and Methods l Programming with Arrays Arrays

ARRAYS 3

Code to enter all seven temperatures

Getting one temperature is easy:

System.out.println("max temperature for day 1 ?");

temperature1 = Double.parseDouble

(keyboard.readLine( ));

Page 4: ARRAYS 1 TOPIC 8 l Array Basics l Arrays and Methods l Programming with Arrays Arrays

ARRAYS 4

Try using a loop?

for (int i=1; i<=7; i++)

{

System.out.println("max temperature for day " + i);

temperature1 = Double.parseDouble(keyboard.readLine( ));

}

Page 5: ARRAYS 1 TOPIC 8 l Array Basics l Arrays and Methods l Programming with Arrays Arrays

ARRAYS 5

Arrays

An array is an ordered list of values

0 1 2 3 4 5 6 7 8 9

79 87 94 82 67 98 87 81 74 91

An array of size N is indexed from zero to N-1

scores

The entire arrayhas a single name

Each value has a numeric index

This array holds 10 values that are indexed from 0 to 9

Page 6: ARRAYS 1 TOPIC 8 l Array Basics l Arrays and Methods l Programming with Arrays Arrays

ARRAYS 6

Arrays

A particular value in an array is referenced using the array name followed by the index in brackets

For example, the expression

scores[2]

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

Page 7: ARRAYS 1 TOPIC 8 l Array Basics l Arrays and Methods l Programming with Arrays Arrays

ARRAYS 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];

Examples:80-element character array:

char[] symbol = new char[80];

100-element array of doubles:double[] reading = new double[100];

Page 8: ARRAYS 1 TOPIC 8 l Array Basics l Arrays and Methods l Programming with Arrays Arrays

ARRAYS 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];

Page 9: ARRAYS 1 TOPIC 8 l Array Basics l Arrays and Methods l Programming with Arrays Arrays

ARRAYS 9

Java Instructions

temperature = new double[7];

Computer Memory

temperature

item of type 'double'

item of type 'double'

item of type 'double'

item of type 'double'

item of type 'double'

item of type 'double'

item of type 'double'

The effect on

computer

memory of

declaring an

array of

values of type

'double'

Page 10: ARRAYS 1 TOPIC 8 l Array Basics l Arrays and Methods l Programming with Arrays Arrays

ARRAYS 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 : temperature[0] second temperature: temperature[1]

Page 11: ARRAYS 1 TOPIC 8 l Array Basics l Arrays and Methods l Programming with Arrays Arrays

ARRAYS 11

Some array terminology

temperature[n + 2]

temperature[n + 2]

temperature[n + 2]

temperature[n + 2] = 32;

Array name

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

Note that "element" may refer to either a single indexed variable in the arrayor the value of a single indexed variable.

Value of the indexed variable- also called an element of the array

Page 12: ARRAYS 1 TOPIC 8 l Array Basics l Arrays and Methods l Programming with Arrays Arrays

ARRAYS 12

ACCESSING ARRAY ELEMENTS

temperature[0] = Double.parseDouble(keyboard.readLine( ));

System.out.println(temperature[5]);

System.out.println ("temperature for day 1 is ”

+ temperature[0]);

temperature[4] = temperature[4] * 2;

if (temperature[2] >= 18)

{

System.out.println("it was hot today");

}

Page 13: ARRAYS 1 TOPIC 8 l Array Basics l Arrays and Methods l Programming with Arrays Arrays

ARRAYS 13

USING A LOOP TO ENTER VALUES INTO AN ARRAY

for(int i = 0; i < 7; i++)

{

System.out.println("max temperature for day ”

+(i+1));

temperature[i] = Double.parseDouble(keyboard.readLine( ));

}

Page 14: ARRAYS 1 TOPIC 8 l Array Basics l Arrays and Methods l Programming with Arrays Arrays

ARRAYS 14

THE 'length' ATTRIBUTE

for (int i = 0; i < 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.

Page 15: ARRAYS 1 TOPIC 8 l Array Basics l Arrays and Methods l Programming with Arrays Arrays

ARRAYS 15

EXAMPLE:Array 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(System.in));

public static void main(String[] args){

double[] temperature = new double[7];int index;double sum = 0.0, average;System.out.println(“Enter 7 temperature readings”);

 for (index = 0; index < 7; index++){ temperature[index] =

Double.parseDouble(keyboard.readLine()); sum = sum + temperature[index];}

Page 16: ARRAYS 1 TOPIC 8 l Array Basics l Arrays and Methods l Programming with Arrays Arrays

ARRAYS 16

average = sum / 7;System.out.println(“The average temperature is “ + average); System.out.println(“The temperatures are : “);for (index = 0; index < 7; index++);

{ if (temperature[index] < average)

System.out.println(temperature[index] + “ below average”); else

if (temperature[index] > average) System.out.println(temperature[index] + “ above

average”);else System.out.println(temperature[index] + “ is the

average”);}

}}

Page 17: ARRAYS 1 TOPIC 8 l Array Basics l Arrays and Methods l Programming with Arrays Arrays

ARRAYS 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'};

Page 18: ARRAYS 1 TOPIC 8 l Array Basics l Arrays and Methods l Programming with Arrays Arrays

ARRAYS 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};

Subscript: 0 1 2 3Value: 97 86 92 71

Page 19: ARRAYS 1 TOPIC 8 l Array Basics l Arrays and Methods l Programming with Arrays Arrays

ARRAYS 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.

Page 20: ARRAYS 1 TOPIC 8 l Array Basics l Arrays and Methods l Programming with Arrays Arrays

ARRAYS 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

Page 21: ARRAYS 1 TOPIC 8 l Array Basics l Arrays and Methods l Programming with Arrays Arrays

ARRAYS 21

Array size

FIXED-SIZE ARRAY DECLARATION

int[] number = new int[100];

Problems??o Don’t always know array size at compile time.

Page 22: ARRAYS 1 TOPIC 8 l Array Basics l Arrays and Methods l Programming with Arrays Arrays

ARRAYS 22

Some operations on arrays:

Initialize Input data Output stored data Find largest/smallest/sum/average of elements

Page 23: ARRAYS 1 TOPIC 8 l Array Basics l Arrays and Methods l Programming with Arrays Arrays

ARRAYS 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 int[arraySize]; // Create array

Page 24: ARRAYS 1 TOPIC 8 l Array Basics l Arrays and Methods l Programming with Arrays Arrays

ARRAYS 24

Code to Initialize Array to Specific Value (10.00)

for(index = 0; index < sale.length; index++) sale[index] = 10.00;

Page 25: ARRAYS 1 TOPIC 8 l Array Basics l Arrays and Methods l Programming with Arrays Arrays

ARRAYS 25

Code to Read Data into Array

for(index = 0; index < sale.length; index++) sale[index] = Integer.parseInt(keyboard.readLine());

Page 26: ARRAYS 1 TOPIC 8 l Array Basics l Arrays and Methods l Programming with Arrays Arrays

ARRAYS 26

Code to Print Array

for(index = 0; index < sale.length; index++) System.out.print(sale[index] + " ");

Page 27: ARRAYS 1 TOPIC 8 l Array Basics l Arrays and Methods l Programming with Arrays Arrays

ARRAYS 27

Code to Find Sum & Average of Array

sum = 0;for(index = 0; index < sale.length; index++) sum = sum + sale[index];

if(sale.length != 0) average = sum / sale.length;else average = 0.0;

Page 28: ARRAYS 1 TOPIC 8 l Array Basics l Arrays and Methods l Programming with Arrays Arrays

ARRAYS 28

Determining Largest Element in Array

maxIndex = 0;for(index = 1; index < sale.length; index++) if(sale[maxIndex] < sale[index]) maxIndex = index;

largestSale = sale[maxIndex];

Page 29: ARRAYS 1 TOPIC 8 l Array Basics l Arrays and Methods l Programming with Arrays Arrays

ARRAYS 29

Determining Largest Element in Array