Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "ARRAYS 1 TOPIC 8 l Array Basics l Arrays and Methods l Programming with Arrays Arrays."— Presentation transcript:

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

2 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 }

3 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( ));

4 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( )); }

5 ARRAYS 5 Arrays l 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 array has a single name Each value has a numeric index This array holds 10 values that are indexed from 0 to 9

6 ARRAYS 6 Arrays l A particular value in an array is referenced using the array name followed by the index in brackets l For example, the expression scores[2] refers to the value 94 (the 3rd value in the array) l That expression represents a place to store a single integer and can be used wherever an integer variable can be used

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

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

9 ARRAYS 9 Java Instructions temperature = new double[7]; Computer Memory temperature item of type 'double' The effect on computer memory of declaring an array of values of type 'double'

10 ARRAYS 10 NAMING OF ARRAY ELEMENTS l Each element in an array shares the same name as the array. l The individual elements are then uniquely identified by an additional index value. l Array indices start from 0 (and not from 1). l This index value is always enclosed in square brackets : first temperature : temperature[0] second temperature: temperature[1]

11 ARRAYS 11 Some array terminology 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 array or the value of a single indexed variable. Value of the indexed variable - also called an element of the array

12 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"); }

13 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( )); }

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

15 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]; }

16 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”); }

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

18 ARRAYS 18 Subscript range l Array subscripts use zero-numbering »the first element has subscript 0 »the second element has subscript 1 »etc. - the n th element has subscript n-1 »the last element has subscript length-1 l For example: int[] scores = {97, 86, 92, 71};

19 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 l 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 ARRAYS 20 Good programming practice l 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 l Do not count on default initial values for array elements »explicitly initialize elements in the declaration or in a loop

21 ARRAYS 21 Array size l FIXED-SIZE ARRAY DECLARATION int[] number = new int[100];  Problems?? oDon’t always know array size at compile time.

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

23 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

24 ARRAYS 24 Code to Initialize Array to Specific Value (10.00) for(index = 0; index < sale.length; index++) sale[index] = 10.00;

25 ARRAYS 25 Code to Read Data into Array for(index = 0; index < sale.length; index++) sale[index] = Integer.parseInt(keyboard.readLine());

26 ARRAYS 26 Code to Print Array for(index = 0; index < sale.length; index++) System.out.print(sale[index] + " ");

27 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;

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

29 ARRAYS 29 Determining Largest Element in Array


Download ppt "ARRAYS 1 TOPIC 8 l Array Basics l Arrays and Methods l Programming with Arrays Arrays."

Similar presentations


Ads by Google