arrays - david r. cheriton school of computer sciencedvogel/cs105f16/materials/lectures/08...
TRANSCRIPT
Arrays
• Object Creation and "dot syntax"
• Array Operation Idiom
CS 105 | 08 Arrays 1
circleracers (one racer)
CS 105 | 08 Arrays 2
// the x-position of the racerfloat x = 0;
void draw() {background(245); // white
drawRacer(x, 40, 1);x += 1;
}
// draw a racer at position x,y// draw the racer numbervoid drawRacer(float x, float y, int number) {...
circleracers (three racers)
CS 105 | 08 Arrays 3
// the x-position of the racersfloat x1 = 0;float x2 = 0;float x3 = 0;
void draw() {background(245); // white
drawRacer(x1, 40, 1);x1 += random(0, 3);
drawRacer(x2, 80, 2);x2 += random(0, 3);
drawRacer(x3, 120, 3);x3 += random(0, 3);
CS 105 | 08 Arrays 4
float x1 = 0;float x2 = 0;float x3 = 0;float x4 = 0;float x5 = 0;float x6 = 0;float x7 = 0;float x8 = 0;float x9 = 0;float x10 = 0;float x11 = 0;float x12 = 0;float x13 = 0;float x14 = 0;float x15 = 0;float x16 = 0;float x17 = 0;float x18 = 0;float x19 = 0;float x20 = 0;
drawRacer(x1, 40, i);x1 += random(0, 3);
drawRacer(x2, 80, i);x2 += random(0, 3);
drawRacer(x3, 120, i);x3 += random(0, 3);
drawRacer(x4, 160, i);x4 += random(0, 3);
drawRacer(x5, 200, i);x5 += random(0, 3);
drawRacer(x6, 240, i);x6 += random(0, 3);
drawRacer(x7, 280, i);x7 += random(0, 3);
drawRacer(x8, 320, i);x8 += random(0, 3);
drawRacer(x9, 360, i);x9 += random(0, 3);
drawRacer(x10, 400, i);x10 += random(0, 3);
drawRacer(x11, 440, i);x11 += random(0, 3);
drawRacer(x12, 480, i);x12 += random(0, 3);
drawRacer(x13, 520, i);x13 += random(0, 3);
drawRacer(x14, 560, i);x14 += random(0, 3);
drawRacer(x15, 600, i);x15 += random(0, 3);
drawRacer(x16, 640, i);x16 += random(0, 3);
drawRacer(x17, 680, i);x17 += random(0, 3);
drawRacer(x18, 720, i);x18 += random(0, 3);
drawRacer(x19, 760, i);x19 += random(0, 3);
drawRacer(x20, 800, i);x20 += random(0, 3);;
Array
§ An array is a special variable that holds multiple values.
§ Each value location is called an element.
§ Each element is accessed using a unique index - The index is a whole number: 0, 1, 2, …
CS 105 | 08 Arrays 5
23
a b[]
15 7 -10 66 5
Variable Array
b[0] b[1] b[2] b[3] b[4]
CS 105 | 08 Arrays 6
Declaring an Array
CS 105 | 08 Arrays 7
int[] b;
int a;
array of intstype
int variable type
variable name
array name
Variable (for comparison)
Array declare an array of ints
Creating an Array
§ new is an operator that means “create”
§ we need to “create” the elements so they can hold values- “normal” variables have a single value, no need to create
CS 105 | 08 Arrays 8
int[] b;
b = new int[5];
create an array of 5 ints
typeof values
lengthof array
“create”
Declare and Create an Array in One Step
CS 105 | 08 Arrays 9
int[] b = new int[5];
create an array of 5
ints
declare an array of ints
called b
Declare and Create Array Examples
CS 105 | 08 Arrays 10
boolean[] boxStates;boxStates = new boolean[4];
float[] scores = new float[4];
int[] hues = new int[10];
int num = 5;float[] x = new float[num];float[] y = new float[num];
boolean[] s = new boolean[num * 2];
Valid or Invalid Array Declaration and Creation?
CS 105 | 08 Arrays 11
int[] a = new int[2 * 10];
float[] b = new int[5];
boolean c = new boolean[5];
float[5] d;
int[] e; e = new int[123];
float[] f = float[12];
int[] g = new int[1];
int[] h = new int[0];
Assigning Values to an Array
§ You assign values to each array element using the index
CS 105 | 08 Arrays 12
int[] b = new int[5];
b[3] = 66;
elementindex
assign 66 to element at
index 3
b[3] is the 4th
element
Initializing an Array
§ Initializing an array is when you assign a value to each element after creating the array
§ All elements are initialized to a default value when created- float and int are 0, boolean is false, String is null
CS 105 | 08 Arrays 13
int[] b = new int[5];
b[0] = 15;b[1] = 7;b[2] = -10;b[3] = 66;b[4] = 5;
b[]
15 7 -10 66 5
b[0] b[1] b[2] b[3] b[4]
initi
aliz
ing
Creating and Initializing an Array in One Step
CS 105 | 08 Arrays 14
int[] b = {15, 7, -10, 66, 5};
b[]
15 7 -10 66 5
b[0] b[1] b[2] b[3] b[4]
create an array of 5 intsand initialize it to these values
Using Arrays
§ Use array elements just like variables
CS 105 | 08 Arrays 15
int[] b = new int[5];b[0] = 15;b[1] = random(-100, 100);println(b[2]);float c = b[0] * 100;b[3] = b[3] + 5;ellipse(b[0], b[1], b[2], b[2]);if (b[3] > 5) { ...
You must create an array before using it
§ if an array hasn't been created, it has no elements- trying to access an "uncreated array", is a runtime error:
CS 105 | 08 Arrays 16
int[] b;b[0] = 666; // errorb[4] = 678; // error
b[]
?????
Valid Index Values
§ index must be between 0 and one less than array length - if array length is 5, index can be 0, 1, 2, 3, or 4
- otherwise, it's a runtime error:
CS 105 | 08 Arrays 17
int[] b = new int[5];b[-1] = 123; // errorb[5] = 123; // error
b[]
15 7 -10 66 5
b[0] b[1] b[2] b[3] b[4]
Valid Index Types
§ an index must be an int type
§ otherwise, it's a syntax error
CS 105 | 08 Arrays 18
int[] b = new int[5];b[1.0] = 15; // errorfloat f = 2;b[f] = 7; // error
b[]
15 7 -10 66 5
b[0] b[1] b[2] b[3] b[4]
§ you can convert an int using int() b[int(f)] = 7; // ok
(error demos)
CS 105 | 08 Arrays 19
int[] b = new int[5];float f = 1;
void setup() {println("start"); println(b[5]); // try -1, 1.0, f println("stop");
}
What is printed to the console ?
CS 105 | 08 Arrays 20
A. 1
B. 2
C. 3
D. 4
E. 5
int[] bar = new int[4];
void setup() {bar[0] = 5;bar[1] = 4;bar[2] = 3;bar[3] = 2;
println(bar[1]); }
What is printed to the console ?
CS 105 | 08 Arrays 21
A. 1
B. 2
C. 3
D. 4
E. 5
int[] bar = new int[5];
void setup() {bar[0] = 1;bar[1] = 2;bar[2] = 3;bar[3] = 4;bar[4] = bar[bar[1]];
println(bar[4]); }
circleracers (with array)
CS 105 | 08 Arrays 22
// the x-position of the racersfloat[] x = new float[3];
void draw() {background(245); // white
drawRacer(x[0], 40, 1);x[0] += random(0, 3);
drawRacer(x[1], 80, 2);x[1] += random(0, 3);
drawRacer(x[2], 120, 3);x[2] += random(0, 3);
}
Variables for Indices
§ Use variables or return values for indices
CS 105 | 08 Arrays 23
int[] b = new int[5];int i = 0;b[i] = 15;b[i + 1] = 7;b[int(random(0, 5))] = 1000000;
int() function converts to int,
otherwise a syntax error
circleracers (with array)
CS 105 | 08 Arrays 24
// the x-position of the racersfloat[] x = new float[3];
void draw() {background(245); // white
int i = 0;
drawRacer(x[i], 40, i + 1);x[i] += random(0, 3);i++;
drawRacer(x[i], 80, i + 1);x[i] += random(0, 3);i++;
drawRacer(x[i], 120, i + 1);x[i] += random(0, 3);
}
circleracers (with array and loop)
CS 105 | 08 Arrays 25
// the x-position of the racersfloat[] x = new float[3];
void draw() {background(245); // white
int i = 0;while (i < 3) {// the y position is a "function of" ifloat y = (i + 1) * 40;drawRacer(x[i], y, i + 1);x[i] += random(0, 3);i++;
}}
How many Xs are printed to the console?
CS 105 | 08 Arrays 26
A. 0
B. 1
C. 4
D. 5
E. 6
for (int i = 0; i < 5; i++ ) {print("X");
}
What is printed to the console ?
CS 105 | 08 Arrays 27
A. 0
B. 1
C. 4
D. 5
E. nothing, it’s an error
int[] arr = new int[5];
for (int i = 0; i < 5; i++) {arr[i] = i;
}
println(arr[4]);
Array Length
§ Arrays know their own length- Arrays are objects- you access array length using object “dot syntax”
CS 105 | 08 Arrays 28
int[] b = new int[5];println(b.length); // prints 5
b[b.length – 1] = 123; // okb[b.length] = 123; // error
say “b dot length”
circleracers (with array and loop)
CS 105 | 08 Arrays 29
// the x-position of the racersfloat[] x = new float[5];
void draw() {background(245); // white
int i = 0;while (i < x.length) {// the y position is a "function of" ifloat y = (i + 1) * 40;drawRacer(x[i], y, i + 1);x[i] += random(0, 3);i++;
}}
Array Operation Idiom
§ Looping through an entire array to apply some operation to all elements is a common operation.
CS 105 | 08 Arrays 30
// initialize array elements to same valuefor (int i = 0; i < myArray.length; i++) {myArray[i] = 50;
}
// initialize array elements to random valuefor (int i = 0; i < myArray.length; i++) {myArray[i] = random(0, 100);}
Array Operation: Sum all Elements
§ Compute the total sum for all elements in an array by adding them one by one to an accumulator variable.
CS 105 | 08 Arrays 31
// compute the sum of all elementsfloat total = 0; for (int i = 0; i < myArray.length; i++) {total += myArray[i];
}println("total:", total);
Array Operation: Average Element Value
§ Sum all elements in an array and divide total by the length of the array to compute the average element size.
CS 105 | 08 Arrays 32
// calculate the average value float total = 0;for (int i = 0; i < myArray.length; i++) {total += myArray[i];
}float average = total / myArray.length;println("average:", average);
Array Operation: Find Largest Element Value
§ Search the array to find the largest element value- Start by guessing that the largest element is the first one- check all other elements one-by-one to see if any are larger- if a larger one is found, use it as the largest element
CS 105 | 08 Arrays 33
// find the largest element// (assuming myArray has at least 1 element)float largest = myArray[0];for (int i = 1; i < myArray.length; i++) {if (myArray[i] > largest) {largest = myArray[i];
}}println("largest:", largest);
Array Operation: Find Largest Element Index
§ Search the array to find the index with largest element value- Start by guessing that index 0 is the largest element index - check all other elements one-by-one to see if any are larger- if larger one is found, use it’s index as the largest element index
CS 105 | 08 Arrays 34
// find the index of the largest element// (assuming myArray has at least 1 element)int indexOfLargest = 0;for (int i = 1; i < myArray.length; i++) {if (myArray[i] > myArray[indexOfLargest]) {indexOfLargest = i;
}}println("index of largest:", indexOfLargest);println("largest:", myArray[indexOfLargest]);
Asymptotic Runtime of Algorithms
§ O(1) and O(N) … “big Oh”
§ How many operations does it take to print one element?
print(myArray[i]);
§ How many operations does it take to add all elements?// compute the sum of all elementsfloat total = 0; for (int i = 0; i < myArray.length; i++) {total += myArray[i];
}println("total:", total);
CS 105 | 08 Arrays 35
Arrays as Function Parameters and Arguments
§ float means a single floating point value
§ float[] means an array of floating point values
CS 105 | 08 Arrays 36
void func(float[] a) {…
}
void func(float f) {…
}
largestValue (in arrayoperations code)
CS 105 | 08 Arrays 37
// return the largest element in array a// (assuming a has at least 1 element)float largestValue(float[] a) {
float largest = a[0];for (int i = 1; i < a.length; i++) {if (a[i] > largest) {largest = a[i];
}}return largest;
}
arrayforest
CS 105 | 08 Arrays 38
float[] treeX = {166, 90, 77, 30, 110, 131, 55 };float[] treeLeafColour = new float[treeX.length];
void setup() {... // initialize to random tint of greenfor (int i = 0; i < treeLeafColour.length; i++ ) {
treeLeafColour[i] = random(64, 130); }
}
void draw() {... // draw trees for forestfor (int i = 0; i < treeX.length; i++) {
tree(treeX[i], 95, treeLeafColour[i]); }
}
EXTRA: Two Arrays, Shifting Elements in Array
§ Textbook Example 9.6
CS 105 | 08 Arrays 39
EXTRA: snake (LP Example 9-8)
CS 105 | 08 Arrays 40
// Shift array valuesfor (int i = 0; i < xpos.length - 1; i++) {xpos[i] = xpos[i + 1];ypos[i] = ypos[i + 1];
}
// New location at end of arrayxpos[xpos.length - 1] = mouseX; ypos[ypos.length - 1] = mouseY;