Lecture 12 Instructor: Craig Duckett ARRAYS. Announcements Assignment 3 Assignment 3 Revision...

33
BIT115: Introduction to Programming Lecture 12 Instructor: Craig Duckett ARRAYS

Transcript of Lecture 12 Instructor: Craig Duckett ARRAYS. Announcements Assignment 3 Assignment 3 Revision...

Page 1: Lecture 12 Instructor: Craig Duckett ARRAYS. Announcements Assignment 3 Assignment 3 Revision Assignment 4 (and Final Exam) GRADED! RETURNED! Woot! NEXT.

BIT115: Introduction to Programming

Lecture 12Instructor: Craig Duckett

ARRAYS

Page 2: Lecture 12 Instructor: Craig Duckett ARRAYS. Announcements Assignment 3 Assignment 3 Revision Assignment 4 (and Final Exam) GRADED! RETURNED! Woot! NEXT.

AnnouncementsAssignment 3

Assignment 3 Revision

Assignment 4 (and Final Exam)

GRADED! RETURNED! Woot!

Due NEXT Monday, August 17th, by midnight

Due Monday, August 24th, by midnight

Extra Credit 01 (I'll go over this next Monday)Due Wednesday, August 26th, by midnight

Page 3: Lecture 12 Instructor: Craig Duckett ARRAYS. Announcements Assignment 3 Assignment 3 Revision Assignment 4 (and Final Exam) GRADED! RETURNED! Woot! NEXT.

• Assignment 1 GRADED

• Assignment 2 GRADED

• Assignment 1 Revision GRADED

• Assignment 2 Revision GRADED

• Assignment 3 GRADED

• Assignment 3 Revision DUE Lecture 13, Monday, August 17th, by midnight

• Assignment 4 DUE Lecture 15, Monday, August 24th, by midnightNO REVISION AVAILABLE

• Extra Credit 01 DUE Lecture 15, Wednesday, August 26th, by midnight

3

Assignment Announcements

Page 4: Lecture 12 Instructor: Craig Duckett ARRAYS. Announcements Assignment 3 Assignment 3 Revision Assignment 4 (and Final Exam) GRADED! RETURNED! Woot! NEXT.

Today’s Topics• The "Official" Introduction to Arrays• Chapter 10.2: Creating Arrays• Chapter 10.5: Arrays of Primitives• Chapter 10.1.1-10.1.7: Arrays of Objects [If Time]

Page 5: Lecture 12 Instructor: Craig Duckett ARRAYS. Announcements Assignment 3 Assignment 3 Revision Assignment 4 (and Final Exam) GRADED! RETURNED! Woot! NEXT.

And now ...The Quiz

Page 6: Lecture 12 Instructor: Craig Duckett ARRAYS. Announcements Assignment 3 Assignment 3 Revision Assignment 4 (and Final Exam) GRADED! RETURNED! Woot! NEXT.

Introduction to ArraysWhat is an Array?

Primitive variables are designed to hold only one value at a time.Arrays allow us to create a collection of like values that are

indexed.An array can store any type of data but only one type of data at a

time.An array is a list of data elements.

Let’s see what this all means...

Page 7: Lecture 12 Instructor: Craig Duckett ARRAYS. Announcements Assignment 3 Assignment 3 Revision Assignment 4 (and Final Exam) GRADED! RETURNED! Woot! NEXT.

Introduction to ArraysWhat is an Array?So far, you have been working with variables that hold only one value. The integer variables you have set up have held only one number (and next week we will see how string variables will hold one long string of text).

An array is a collection to hold more than one value of the same data type at a time. It's like a list of items—a list of integers, or a list of doubles, or a list of chars, or a list of strings, etc

Think of an array as like the columns in a spreadsheet. You can have a spreadsheet with only one column, or several columns.

The data held in a single-list (one-dimensional) arraymight look like this:

index grades

0 100

1 89

2 96

3 100

4 98

Page 8: Lecture 12 Instructor: Craig Duckett ARRAYS. Announcements Assignment 3 Assignment 3 Revision Assignment 4 (and Final Exam) GRADED! RETURNED! Woot! NEXT.

Introduction to ArraysNow, the way we might have declared data like this up until now is to do something along these lines:

int value1 = 100;int value2 = 89;int value3 = 96;int value4 = 100;int value5 = 98;

However, if we knew before hand that we were going to be declaring five int integers (or ten, or fifteen, etc), we could accomplish the same type of declaration by using an array.

index grades

0 100

1 89

2 96

3 100

4 98

NOTE Arrays must be of the same data type, i.e., all integers (whole numbers) or all doubles (floating-point numbers) or all strings (text characters)—you cannot “mix-and-match” data types in an array.

To set up an array of numbers like that in the table above, you have to tell Java what type of data is going into the array, then how many positions the array has. You’d set it up like this:

int[ ] grades;

Page 9: Lecture 12 Instructor: Craig Duckett ARRAYS. Announcements Assignment 3 Assignment 3 Revision Assignment 4 (and Final Exam) GRADED! RETURNED! Woot! NEXT.

Introduction to Arraysindex grades

0 100

1 89

2 96

3 100

4 98

int[ ] grades;

The only difference between setting up a primitive integer variable and an array is a pair of square brackets [ ] after the data type.

The square brackets are enough to tell Java that you want to set up an array. The name of the declared array above is grades.

Just like primitive variables, you can call them almost anything you like (except Java defined keywords). While the square brackets tells Java you want to set up an array, it doesn't say how many positions the array should hold. To do that, you have to set up a new array object:

int[ ] grades;grades = new int[5]; // <-- New array object

In between the square brackets you need the pre-defined size of the array. The size is how many slots (elements) the array should hold. If you prefer, you can put all that on one line:

int[ ] grades = new int[5]; // Done at same time

Page 10: Lecture 12 Instructor: Craig Duckett ARRAYS. Announcements Assignment 3 Assignment 3 Revision Assignment 4 (and Final Exam) GRADED! RETURNED! Woot! NEXT.

Introduction to Arrays: Example import java.util.*;

public class Array_Demo extends Object { public static void main(String[] args) { int [] grades = new int[5]; grades[0] = 100; grades[1] = 89; grades[2] = 96; grades[3] = 100; grades[4] = 98;

// <-- Something especially groovy happens here!

} }

Page 11: Lecture 12 Instructor: Craig Duckett ARRAYS. Announcements Assignment 3 Assignment 3 Revision Assignment 4 (and Final Exam) GRADED! RETURNED! Woot! NEXT.

Introduction to Arraysindex grades

0 100

1 89

2 96

3 100

4 98

When you declare an array with a given data type, name and number, like grades = new int[5];

you are reserving a collection space in memory by that name, sized according to data type, and large enough to separately contain enough data for the declared size.

grades variable

Element1

The number inside the brackets is the array’s size declarator or length. It indicates

the number of elements, or values, the array can hold. In the declaration above, grades references an array with enough memory being reserved for five (5) integer values.

Element2

Element3

Element4

Element5

STEP 1: Declare VariableSTEP 2: Allocate MemorySTEP 3: Initialize Elements

Page 12: Lecture 12 Instructor: Craig Duckett ARRAYS. Announcements Assignment 3 Assignment 3 Revision Assignment 4 (and Final Exam) GRADED! RETURNED! Woot! NEXT.

Introduction to Arrays: Example import java.util.*;

public class Array_Demo extends Object { public static void main(String[] args) { int [] grades = new int[5]; grades[0] = 100; grades[1] = 89; grades[2] = 96; grades[3] = 100; grades[4] = 98;

// <-- Something especially groovy happens here!

} }

Page 13: Lecture 12 Instructor: Craig Duckett ARRAYS. Announcements Assignment 3 Assignment 3 Revision Assignment 4 (and Final Exam) GRADED! RETURNED! Woot! NEXT.

index grades

0 100

1 89

2 96

3 100

4 98

0 1 2 3 4

32-bits 32-bits 32-bit 32-bits 32-bits

0 0 0 0 0

grades is a named reserved space set aside to hold exactly five [5] 32-bit elements all initializing to a value of zero 0. As we have learned about programming languages, the “index” always starts at 0, not 1, and procedes until the size of the array is reached. In our example, since we declared [5] the array element index starts with 0 and ends at 4.

array element index

space reserved for data

value initialized in element

0 1 2 3 4

100 89 96 100 98

grades[0] = 100; // Steps 3grades[1] = 89;grades[2] = 96;grades[3] = 100;grades[4] = 98;

grades = new int[5];

grades = new int[5]; // <-- Steps 1 & 2

grades

5

STEP 1: Declare VariableSTEP 2: Allocate MemorySTEP 3: Initialize Elements

Page 14: Lecture 12 Instructor: Craig Duckett ARRAYS. Announcements Assignment 3 Assignment 3 Revision Assignment 4 (and Final Exam) GRADED! RETURNED! Woot! NEXT.

Introduction to Arrays: Example import java.util.*;

public class Array_Demo extends Object { public static void main(String[] args) { int [] grades = new int[5]; grades[0] = 100; grades[1] = 89; grades[2] = 96; grades[3] = 100; grades[4] = 98;

// <-- Something especially groovy happens here!

} }

Page 15: Lecture 12 Instructor: Craig Duckett ARRAYS. Announcements Assignment 3 Assignment 3 Revision Assignment 4 (and Final Exam) GRADED! RETURNED! Woot! NEXT.

So we are telling Java to set up an array with 5 positions in it. After this line is executed, Java will assign default values for the array. Because we've set up an integer array, the default values for all 5 positions will be zero ( 0 ). To assign values to the various positions in an array, you do it in the normal way:

grades[0] = 100;grades[1] = 89;grades[2] = 96;grades[3] = 100;grades[4] = 98;

If you know what values are going to go in the array, you can also set them up like this:

int[ ] grades = { 100, 89, 96, 100, 98 }; // Java treats as new instance

Introduction to Arraysindex grades

0 100

1 89

2 96

3 100

4 98

You can also declare the int separately and call it by its given name, like this:

int testScores = 5;int[ ] grades = new int[testScores];

(Whether you call the number inside the brackets or a named variable is up to your particular style of coding and preference.)

grades [0] = 100;grades [1] = 89;grades [2] = 96;grades [3] = 100;grades [4] = 98;

This is called the index

Length of the array is equal to the number of slots declared{

Page 16: Lecture 12 Instructor: Craig Duckett ARRAYS. Announcements Assignment 3 Assignment 3 Revision Assignment 4 (and Final Exam) GRADED! RETURNED! Woot! NEXT.

import java.util.*;

public class Array_Demo extends Object { public static void main(String[] args) { // Setting up the integer 5-element array: int [] grades = new int[5]; grades[0] = 100; grades[1] = 89; grades[2] = 96; grades[3] = 100; grades[4] = 98; // Of course you could have done it this way: // int [] grades = {100, 89, 96, 100, 98}; int i; for(i = 0; i < grades.length; i++) { System.out.println("Grade " + (i + 1) + " is: " + grades[i]); } } }

Page 17: Lecture 12 Instructor: Craig Duckett ARRAYS. Announcements Assignment 3 Assignment 3 Revision Assignment 4 (and Final Exam) GRADED! RETURNED! Woot! NEXT.

Arrays of Primitives: Overview

An array is an object so it needs an object reference.// Declare a reference to an array that will hold integers. int[] numbers;

The next step creates the array and assigns its address to the numbers variable// Create a new array that will hold 6 integers.numbers = new int[6];

Array element values are initialized to 0 by default.Array indexes always start at 0.

0index 0

0index 1

0index 2

0index 3

0index 4

0index 5

Page 18: Lecture 12 Instructor: Craig Duckett ARRAYS. Announcements Assignment 3 Assignment 3 Revision Assignment 4 (and Final Exam) GRADED! RETURNED! Woot! NEXT.

Arrays of Primitives: Overview It is possible to declare an array reference and create it in

the same statement.

int[] numbers = new int[6];

Arrays may be of any type.float[] temperatures = new float[100];char[] letters = new char[41];long[] units = new long[50];double[] sizes = new double[1200];

• long - 8 bytes signed. Ranges from -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807.

• float - 4 bytes. Covers a range from 1.40129846432481707e-45 to 3.40282346638528860e+38 (positive or negative).

• double - 8 bytes. Covers a range from 4.94065645841246544e-324d to 1.79769313486231570e+308d (positive or negative).

• char - 2 bytes, unsigned, Unicode, 0 to 65,535. Chars are not the same as bytes, ints, shorts or Strings.

Page 19: Lecture 12 Instructor: Craig Duckett ARRAYS. Announcements Assignment 3 Assignment 3 Revision Assignment 4 (and Final Exam) GRADED! RETURNED! Woot! NEXT.

Arrays of Primitives: OverviewThe array length must be a non-negative

number.

It may be a literal value, a constant, or variable.

int arraySize = 6; ( or final int ARRAY_SIZE = 6; )

int[] numbers = new int[arraySize];

Once created, an array length is fixed and cannot be changed.

Page 20: Lecture 12 Instructor: Craig Duckett ARRAYS. Announcements Assignment 3 Assignment 3 Revision Assignment 4 (and Final Exam) GRADED! RETURNED! Woot! NEXT.

Accessing the Elements of an Array

numbers[0]

0numbers[1]

0numbers[2]

0numbers[3]

0numbers[4]

0numbers[5]

20

An array is accessed by:

the reference name (e.g., numbers)a subscript that identifies which element in the array to

access.

numbers[0] = 20; //pronounced "numbers sub zero"

Name Subscript

Page 21: Lecture 12 Instructor: Craig Duckett ARRAYS. Announcements Assignment 3 Assignment 3 Revision Assignment 4 (and Final Exam) GRADED! RETURNED! Woot! NEXT.

Inputting and Outputting Array Elements

Array elements can be treated as any other variable.

They are simply accessed by the same name and a subscript. See example: ArrayDemo1.java

Array subscripts can be accessed using variables (such as for loop counters).See example: ArrayDemo2.java

Page 22: Lecture 12 Instructor: Craig Duckett ARRAYS. Announcements Assignment 3 Assignment 3 Revision Assignment 4 (and Final Exam) GRADED! RETURNED! Woot! NEXT.

Bounds CheckingArray indexes always start at zero and continue to (array

length - 1)

int values = new int[10];

This array would have indexes 0 through 9See example: InvalidSubscript.javaIn for loops, it is typical to use i, j, and k as counting

variablesIt might help to think of i as representing the word index

Page 23: Lecture 12 Instructor: Craig Duckett ARRAYS. Announcements Assignment 3 Assignment 3 Revision Assignment 4 (and Final Exam) GRADED! RETURNED! Woot! NEXT.

Watch for “Off-by-One” Errors It is very easy to be “off-by-one” when accessing arrays

// This code has an off-by-one error.int[] numbers = new int[100];for (int i = 1; i <= 100; i++) // Would work with < only{ numbers[i] = 99;}

Here, the equal sign allows the loop to continue on to index 100, but 99 is the last index in the array

This code would throw an ArrayIndexOutOfBoundsException

Page 24: Lecture 12 Instructor: Craig Duckett ARRAYS. Announcements Assignment 3 Assignment 3 Revision Assignment 4 (and Final Exam) GRADED! RETURNED! Woot! NEXT.

Array InitializationWhen relatively few items need to be initialized, an

initialization list can be used to initialize the array

int[]days = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};

The numbers in the list are stored in the array in order:days[0] is assigned 31,days[1] is assigned 28,days[2] is assigned 31,days[3] is assigned 30,etc.

See example: ArrayInitialization.java

Page 25: Lecture 12 Instructor: Craig Duckett ARRAYS. Announcements Assignment 3 Assignment 3 Revision Assignment 4 (and Final Exam) GRADED! RETURNED! Woot! NEXT.

Alternate Array DeclarationPreviously we showed arrays being declared:

int[] numbers;

However, the brackets can also go here:int numbers[];

These are equivalent but the first style is typical (and preferred by most developers/coders).

Multiple arrays can be declared on the same line.int[] numbers, codes, scores;

With the alternate notation each variable must have brackets.int numbers[], codes[], scores;

The scores variable in this instance is simply an int variable.

Page 26: Lecture 12 Instructor: Craig Duckett ARRAYS. Announcements Assignment 3 Assignment 3 Revision Assignment 4 (and Final Exam) GRADED! RETURNED! Woot! NEXT.

Processing Array ContentsProcessing data in an array is the same as any other variable

grossPay = hours[3] * payRate;

Pre and post increment works the same:

int[] score = {7, 8, 9, 10, 11};++score[2]; // Pre-increment operationscore[4]++; // Post-increment operation

See example: PayArray.java

Page 27: Lecture 12 Instructor: Craig Duckett ARRAYS. Announcements Assignment 3 Assignment 3 Revision Assignment 4 (and Final Exam) GRADED! RETURNED! Woot! NEXT.

Processing Array ContentsArray elements can be used in relational operations

if(cost[20] < cost[0]){//statements

}

They can be used as loop conditions:

while(value[count] != 0){//statements

}

Page 28: Lecture 12 Instructor: Craig Duckett ARRAYS. Announcements Assignment 3 Assignment 3 Revision Assignment 4 (and Final Exam) GRADED! RETURNED! Woot! NEXT.

Array LengthArrays are objects and provide a public field named length that

is a constant that can be tested

double[] temperatures = new double[25];

The length of this array is 25.

The length of an array can be obtained via its length constant

int size = temperatures.length;

The variable size will contain 25.

Page 29: Lecture 12 Instructor: Craig Duckett ARRAYS. Announcements Assignment 3 Assignment 3 Revision Assignment 4 (and Final Exam) GRADED! RETURNED! Woot! NEXT.

The Enhanced for LoopSimplified array processing (read only)Always goes through all elementsGeneral:

for(datatype elementVariable : array) statement;

Example:

int[] numbers = {3, 6, 9};for(int val : numbers) // <-- Only two parts. You can read the line as // "iterate on elements from the collection named numbers. The current // element will be referenced by the int val."

{System.out.println("The next value is " + val);

}

Page 30: Lecture 12 Instructor: Craig Duckett ARRAYS. Announcements Assignment 3 Assignment 3 Revision Assignment 4 (and Final Exam) GRADED! RETURNED! Woot! NEXT.

The Enhanced for Loopint[] numbers = {3, 6, 9};

for(int val : numbers) {System.out.println("The next value is " + val);

}

Java knows an Enhanced for loop when it sees one (the colon gives it away), so instead of using a counter as with the first part of a typical loop, it just looks for the length of the named array.

As it loops it grabs the data from each subscript (part 1 of the enhanced for) that belongs to the named array (part 2 of the enhanced for) and walks (or auto-increments) the length of the array one element at a time.

Page 31: Lecture 12 Instructor: Craig Duckett ARRAYS. Announcements Assignment 3 Assignment 3 Revision Assignment 4 (and Final Exam) GRADED! RETURNED! Woot! NEXT.

Array SizeThe length constant can be used in a loop to

provide automatic bounding.

for(int i = 0; i < temperatures.length; i++){ System.out.println("Temperature " + i ": " + temperatures[i]);

}

Index subscripts start at 0 and end at one less than the array length.

Page 32: Lecture 12 Instructor: Craig Duckett ARRAYS. Announcements Assignment 3 Assignment 3 Revision Assignment 4 (and Final Exam) GRADED! RETURNED! Woot! NEXT.

Array Terms1. Array – A named collection or list of like data type values (e.g., ints or floats)2. Element – The individual storage location of one part of the array3. Subscript – the number used to access an element; subscripts always start with [0]4. Index – a collection or list of all the subscripts5. Length – the number of elements that make up an array6. Size Declarator – The number which makes up the length of an array when declared

int [] grades = new int[5]; grades[0] = 100; grades[1] = 89; grades[2] = 96; grades[3] = 100; grades[4] = 98;

Page 33: Lecture 12 Instructor: Craig Duckett ARRAYS. Announcements Assignment 3 Assignment 3 Revision Assignment 4 (and Final Exam) GRADED! RETURNED! Woot! NEXT.

33

LECTURE 12: ICE Arrays: