0% found this document useful (0 votes)
20 views

CS REG - Unit 6 (2)

Uploaded by

zhichen.zheng
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

CS REG - Unit 6 (2)

Uploaded by

zhichen.zheng
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 78

Can we solve this problem?

Consider the following program (input underlined):


How many days' temperatures? 7
Day 1's high temp: 45
Day 2's high temp: 44
Day 3's high temp: 39
Day 4's high temp: 48
Day 5's high temp: 37
Day 6's high temp: 46
Day 7's high temp: 53
You entered: [45, 44, 39, 48, 37, 46, 53]
Average temp = 44.6
4 days were above average.

Do we want to store these in separate integer variables?


What if the user want to enter 1000 temperatures? (temp1, temp2,..temp1000?)
UNIT 6 - ARRAY
6.1 - ARRAY CREATION AND ACCESS
6.2 - TRAVERSING ARRAYS
6.3 - ENHANCED FOR LOOP FOR ARRAYS
6.4 - DEVELOPING ALGORITHMS USING ARRAYS
Arrays
• array: object that stores many values of the same type.
• value: One array can only store one type of values (data).
• index: A 0-based integer to access an element from an array.

index 0 1 2 3 4 5 6 7 8 9
value 12 49 -2 26 5 17 -6 84 72 3

index 0 index 4 index 9


value is 12 value is 5 value is 3
Array declaration
type[] name = new type[length];

• Example:
int[] numbers = new int[10];

Note: The size of an array is established at the time of creation and cannot be
changed. Array type can be primitive such as int and boolean or object reference
type such as String or Point.
numbers index 0 1 2 3 4 5 6 7 8 9
value 0 0 0 0 0 0 0 0 0 0
Array declaration
• The length can be any integer expression.

int x = 2 * 3 + 1;
int[] data = new int[x % 5 + 2];
Type Default value
int 0
• Each element initially gets a "zero-
equivalent" value. double 0.0
boolean false
String null
or other object (means, "no object")
Accessing elements
name[index] // access
name[index] = value; // modify
• Example:
int[] numbers = new int[10];
numbers[0] = 27;
numbers[3] = -6;
System.out.println(numbers[0]);
if (numbers[3] < 0) {
System.out.println("Element 3 is negative.");
} index
index 00 11 22 33 44 55 66 77 88 99
value
value 27
0 00 00 0-6 00 00 00 00 00 00
Arrays of other types
double[] results = new double[5];
results[2] = 3.4; index 0 1 2 3 4
results[4] = -0.5; value 0.0 0.0 3.4 0.0 -0.5

boolean[] tests = new boolean[6];


tests[3] = true;
index 0 1 2 3 4 5
value false false false true false false
Arrays of other types
String[] words = new String[5];
words[1] = "hi"; index 0 1 2 3 4
words[3] = "hello"; value null "hi" null "hello" null

index 0 1 2 3 4
Point[] pts = new Point[5]; value null null null
pts[1] = new Point(2, 3);
pts[4] = new Point();
Point Point
x=2 x=0
*Note that each element of the pts array store the reference to a Point object.
y=3 y=0
Using initializer lists
Elements of an array are initialized with a specific value based on the type of the elements:
● Elements of type int are initialized to 0.
● Elements of a reference type are initialized to the reference value null.
● Elements of type double are initialized to 0.0.
double [] listThree = new double [4];
● Elements of type boolean are initialized to false.
boolean [] listFour = new boolean[2];
When we know the values for the array when we create it, an initializer list can be helpful:
double [] grades = {70.5, 88.2, 93.7, 98.7};
Using initializer lists
Elements of an array are initialized with a specific value based on the type of the elements:
● Elements of type int are initialized to 0.
● Elements of a reference type are initialized to the reference value null.
● Elements of type double are initialized to 0.0.
double [] listThree = new double [4];
● Elements of type boolean are initialized to false.
boolean [] listFour = new boolean[2];
When we know the values for the array when we create it, an initializer list can be helpful:
double [] grades = {70.5, 88.2, 93.7, 98.7};
String [] petNames = {“Ember”, “Phoenix”, “Kally”};
Using initializer lists
Elements of an array are initialized with a specific value based on the type of the elements:
● Elements of type int are initialized to 0.
● Elements of a reference type are initialized to the reference value null.
● Elements of type double are initialized to 0.0.
double [] listThree = new double [4];
● Elements of type boolean are initialized to false.
boolean [] listFour = new boolean[2];
When we know the values for the array when we create it, an initializer list can be helpful:
double [] grades = {70.5, 88.2, 93.7, 98.7};
String [] petNames = {“Ember”, “Phoenix”, “Kally”};
Out-of-bounds
• Legal indexes: between 0 and the array's length - 1.
• Reading or writing any index outside this range will throw an
ArrayIndexOutOfBoundsException.

• Example:
int[] data = new int[10];
System.out.println(data[0]); // okay
System.out.println(data[9]); // okay
System.out.println(data[-1]); // exception
System.out.println(data[10]); // exception

index 0 1 2 3 4 5 6 7 8 9
value 0 0 0 0 0 0 0 0 0 0
Accessing array elements
int[] numbers = new int[8];
numbers[1] = 3;
numbers[4] = 99;
numbers[6] = 2;
int x = numbers[1];
numbers[x] = 42;
numbers[numbers[6]] = 11; // use numbers[6] as index
index 0 1 2 3 4 5 6 7
x
value 0 0
3 0
11 0
42 0
99 0 0
2 0
Accessing elements
index 0 1 2 3 4 5 6 7
• Arrays are objects!
value 0 3 0 0 99 0 0 0
int[] numbers = new int[8];
numbers[1] = 3;
numbers[4] = 99;

System.out.println(numbers);
System.out.println(numbers[3]);
d
c
e
d
d
c
Lab: Array Manipulator
getMiddleIndex(): creating a plan
UNIT 6 - ARRAY
6.1 - ARRAY CREATION AND ACCESS
6.2 - TRAVERSING ARRAYS
6.3 - ENHANCED FOR LOOP FOR ARRAYS
6.4 - DEVELOPING ALGORITHMS USING ARRAYS
ESSENTIAL KNOWLEDGE (CED pg. 116)

CON-2.I.1
BASIC ARRAY TRAVERSAL There are standard algorithms that utilize
array
traversals to:
• Determine a minimum or maximum
value
• Compute a sum, average or mode

Accessing the elements of an • Determine if at least one element has a


particular property
array, from a starting point • Determine if all elements have a
particular
to an ending point, for a specific property
reason. • Access all consecutive pairs of elements
• Determine the presence or absence of
duplicate elements
• Determine the number of elements
meeting
specific criteria

CON-2.I.2
There are standard array algorithms that
utilize
traversals to:
• Shift or rotate elements left or right
• Reverse the order of the elements
A QUICK NOTE ABOUT THE MATH CLASS (2.9)
A QUICK NOTE ABOUT THE MATH CLASS (2.9)

USE MATH.RANDOM() TO PRODUCE A RANDOM INTEGER BETWEEN 10 AND 20


INCLUSIVE.
MATH.RANDOM() 0 <= VALUE < 1

MATH.RANDOM() * 11 0 <= VALUE < 11

(INT)(MATH.RANDOM() * 11) 0, 1, 2, 3, 4, … , 9, 10

(INT)(MATH.RANDOM() * 11) + 10 10, 11, 12, 13, 14, … , 19, 20


BASIC ARRAY TRAVERSAL Clean
Copy

(SET EACH VALUE)


-8 10 17 -5 20 -12 5 14 13 -19

0 1 2 3 4 5 6 7 8 9
Accessing the elements of an array, from a starting point
to an ending point, for a specific reason.
for (int i = 0; i < intArray.length; i++){

intArray[i] = (int)(Math.random()*41)-20;

}
BASIC ARRAY TRAVERSAL Clean
Copy

(SET EACH VALUE 2)


-8 0 17 0 20 0 5 0 13 0

0 1 2 3 4 5 6 7 8 9
Accessing the elements of an array, from a starting point
to an ending point, for a specific reason.
for (int i = 0; i < intArray.length; i+=2){

intArray[index] = (int)(Math.random()*41)-20;

}
BASIC ARRAY TRAVERSAL Clean
Copy

(DISPLAY EACH VALUE)


-8 10 17 -5 20 -12 5 14 13 -19

0 1 2 3 4 5 6 7 8 9
Accessing the elements of an array, from a starting point
to an ending point, for a specific reason.
for (int i = 0; i < intArray.length; i++){

System.out.print(intArray[i] + “ “);

}
Bounds Errors
for (int i = 0; i ≤ intArray.length; i++){

System.out.print(intArray[i] + “ “);

}
● When using loops to access array elements, we need to be careful with the condition in order to
avoid an ArrayIndexOutOfBoundsException being thrown.
Bounds Errors Will not
access the
for (int i = 0; i < intArray.length -1; i++){ last
element
System.out.print(intArray[i] + “ “);

} Will not
access the
first
for (int i = 1; i < intArray.length; i++){
element
System.out.print(intArray[i] + “ “);

}
BASIC ARRAY TRAVERSAL
(COUNT OCCURRENCES)
-8 10 17 -5 20 -12 5 14 13 -19

0 1 2 3 4 5 6 7 8 9
Accessing the elements of an array, from a starting point
to an ending point, for a specific reason.
int counter = 0;
for (int i = 0; i < intArray.length; i++){
if (intArray[i] == -12){
counter++
}
}
BASIC ARRAY TRAVERSAL
(FINDING MINIMUM VALUE)
-8 10 17 -5 20 -12 5 14 13 -19

0 1 2 3 4 5 6 7 8 9
Accessing the elements of an array, from a starting point
to an ending point, for a specific reason.
int min = intArray[0];
for (int i = 0; i < intArray.length; i++){
if (intArray[i] < min){
min = intArray[i];
}
}
BASIC ARRAY TRAVERSAL
(FINDING MAXIMUM VALUE)
-8 10 17 -5 20 -12 5 14 13 -19

0 1 2 3 4 5 6 7 8 9
Accessing the elements of an array, from a starting point
to an ending point, for a specific reason.
int max = intArray[0];
for (int i = 0; i < intArray.length; i++){
if (intArray[i] > max){
max = intArray[i];
}
}
String
yellow

String String

red blue

list

0 1 2

c
e
list 1.1 1.2 1.3 1.4 1.5 1.6 1.7

0 1 2 3 4 5 6
b
list ------ ------
1.1 1.2 ------
1.3 ------
1.4 ------ 1.6
1.5 ------ ------
1.7
1.7 1.6 1.5 1.4 1.3 1.2 1.1

0 1 2 3 4 5 6
FRQ: PalindromicNumbers
Possible solution:
Possible solution2:
Possible solution:
UNIT 6 - ARRAY
6.1 - ARRAY CREATION AND ACCESS
6.2 - TRAVERSING ARRAYS
6.3 - ENHANCED FOR LOOP FOR ARRAYS
6.4 - DEVELOPING ALGORITHMS USING ARRAYS
A) Change nothing – return max

B) Return max in the if block

C) Add a variable to track index and update


inside if block

D) Return the index variable inside the if block

b
Lab1: average value of an int array
public static double calculateAverage(int[] target){
double sum = 0;
for (int i=0; i<target.length; i++){
sum +=target[i];
}
return (double)sum/target.length;

}
// In the main method:
int[] arr1 = {1,3,5,7,9};
System.out.println(calculateAverage(arr1));
UNIT 6 - ARRAY
6.1 - ARRAY CREATION AND ACCESS
6.2 - TRAVERSING ARRAYS
6.3 - ENHANCED FOR LOOP FOR ARRAYS
6.4 - DEVELOPING ALGORITHMS USING ARRAYS
6.3 Enhanced For-Loop (For-Each) for Arrays

To set up a for-each loop,


use for (type variable :
arrayname) where the
type is the type for
elements in the array, and
read it as “for each
variable value in
arrayname”
loopTest2 1 2 3 4 5

0 1 2 3 4

int[] loopTest2 = {1, 2, 3, 4, 5};

for (int value: loopTest2) {

value *= 5;

}
loopTest2 1 2 3 4 5

0 1 2 3 4

int[] loopTest2 = {1, 2, 3, 4, 5};

for (int value: loopTest2) {

value *= 5; 1

value
}
d
FOR-LOOPS VS. FOR-EACH
LOOPS
Risk of
Bound
int[] loopTest1 = {1, 2, 3, 4, 5}; Errors
Display the element
value at each index,
for (int i = 0; i < loopTest1.length; i++) { from the given
EX P OS ITIONS!! starting index up to
USES IND
System.out.println(loopTest1[i]); the given ending
index.
Can be used to access AND modify elements in the array!
}

int[] loopTest2 = {1, 2, 3, 4, 5};


For each integer
value in for (int value: loopTest2) {
loopTest2, EX P OS ITIONS!!
OES N OT USE IND
display value. D
System.out.println(value);
NO Risk of
Bound
Can be used ONLY to access elements in the array!
Errors } Can NOT be used to modify elements in the array!
int[] loopTest1 = {1, 2, 3, 4, 5};

for (int i = 0; i < loopTest1.length; i++) {

loopTest1[i] *= 5;

}
loopTest1 1 2 3 4 5

0 1 2 3 4

int[] loopTest1 = {1, 2, 3, 4, 5};

for (int i = 0; i < loopTest1.length; i++) {

loopTest1[i] *= 5;

}
loopTest1 5 10 15 20 25 i
0 1 2 3 4 0
1
int[] loopTest1 = {1, 2, 3, 4, 5}; 2
for (int i = 0; i < loopTest1.length; i++) { 3
4
loopTest1[i] *= 5; 5
}
int[] loopTest2 = {1, 2, 3, 4, 5};

for (int value: loopTest2) {

value *= 5;

}
loopTest2 1 2 3 4 5

0 1 2 3 4

int[] loopTest2 = {1, 2, 3, 4, 5};

for (int value: loopTest2) {

value *= 5;

}
loopTest2 1 2 3 4 5

0 1 2 3 4

int[] loopTest2 = {1, 2, 3, 4, 5};

for (int value: loopTest2) {

value *= 5; 1

value
}
WHAT’S THE OUTCOME…???

intValues 6 3 1 0 5

0 1 2 3 4

for (int value: intValues) {

System.out.print(intValues[value]);

}
WHAT’S THE OUTCOME…???

intValues 6 3 1 0 5

0 1 2 3 4

for (int value: intValues) {


6

System.out.print(intValues[value]); value

}
WHAT’S THE OUTCOME…???

intValues 6 3 1 0 5

0 1 2 3 4 6
Index Out Of B
ounds Exceptio
n
for (int value: intValues) {
6

System.out.print(intValues[value]); value

intValues[6]
}
Note: limitations of for-each loops
● Enhanced for each loops cannot be used in all situations. Only use for-each
loops when you want to loop through all the values in an array without
changing their values.

● Do not use for each loops if you need the index.


● Do not use for each loops if you need to change the values in the array.
● Do not use for each loops if you want to loop through only part of an array or
in a different order.
c
A
Lab2: reverse all elements in an array
public static int[] reverseArray(int[] target) {
int[] result = new int[target.length];
int j = 0;

for (int i = target.length-1; i >=0; i--){


result[j] = target[i];
j++;
}
return result;

}
Lab3: Right shift all elements in an array
public static int[] rightShift(int[] target){
int[] result = new int[target.length];

for (int i = 0; i<target.length-1; i++){


result[i+1] = target[i];
}

result[0]=target[target.length-1];
return result;

}
FRQ Practice!
• Possible solution for (a)
• 3 possible solutions for (b)

You might also like