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

Unit 6 Note Packet Key

Uploaded by

bibwh.ap.cs.a
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
104 views

Unit 6 Note Packet Key

Uploaded by

bibwh.ap.cs.a
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

Unit 6 – Arrays

Note Packet -- KEY


Lesson 1: One Dimensional Arrays
Objectives
 VAR-2.A: Represent collections of related primitive or object reference data using one-dimensional (1D) array objects.
 VAR-2.B: Traverse the elements in a 1D array.

What is an Array?
 An array is a special type of object than can hold a fixed number of items of the same data type.
 Why? It leads to simpler code.
 If we have a lot of data of the same type, we would need to create lots of individual variables to hold that data.
 For example, let’s say you had a list of 4 songs:

Representing our 4 songs as individual variables Representing our 4 songs as an array

As code, we would have to write out four


separate lines to represent this data:

String song1 = “Our Song”;


String song2 = “Shake It Off”;
 songs represents our array reference variable
String song3 = “All Too Well”;
String song4 = “Red”;  Each song in the array is called an array element
 Each array element is assigned a numerical position called an index
Now imagine we had to do this with hundreds or
thousands of songs in our program.  These start at 0 and increase by one “down” the list
 The length of the array can be accessed at any time using
It would be so difficult to keep track of all the
songs.length
variables!
 The last index of the array is always songs.length – 1

1
Array Creation
 Arrays can be created two ways: when you know the contents at creation and when you do not know the contents.
 If you know the contents of the array when you are ready to create it, you use the following syntax:
o Type[] name = {<content>, <content>, <content>, …};
 Each array element is separated with a comma and is the same data type
 You CANNOT mix data types in an array
 In our example, we would create an array with those four songs as:
o String[] songs = {“Our Song”, “Shake It Off”, “All Too Well”, “Red”};
 If you do not know the contents of the array, you can use the following syntax to create it:
o Type[] name = new Type[length];
 Notice that the new operator is used and in the second set of square brackets, you would put the length of the array you want.
 In our example, we would create an array with a length of four as:
o String[] songs = new String[4];

You can also declare on one line and create it on another:


String[] songs;
songs = new String[4];

Practice: Write a single line creating the following arrays.


An array called numbers for 10 integer An array called flags that holds the values true, false, and An array called grades that will hold 50 double
values. true. values.

int[] numbers = new int[10] boolean[] flags = {true, false, true}; double[] grades = new double[50];

 Once an array is created, the length of the array cannot be changed


 When an array is created with the new operator, the array is filled with the default value of that type
 Recall: Default Types
 int is 0 double is 0.0 boolean is false String or a reference is null
Manipulating Arrays
2
Once an array is created with the new operator, you are no longer able to modify the values using an array creation method:

//this is an error
int[] grades = new int[5];
grades = {89, 99, 85, 82, 93};

Instead, we use the array index to access and modify an array’s contents after it has been created:

int[] grades = new int[5]; 0 1 2 3 4


grades[0] = 89;
grades[1] = 99; 89 99 85 82 93
grades[2] = 85;
grades[3] = 82;
grades[4] = 93;

We can manipulate array elements using any operators as well. What are the contents of grades after the code has executed?

[89, 99, 85, 82, 93]


grades[0] += 5; [94, 99, 85, 82, 93]
grades[1] = grades[1] % 2 + grades[0]; [94, 95, 85, 82, 93]
grades[2] = grades[3]; [94, 95, 82, 82, 93]
grades[3] = grades[2] + 10; [94, 95, 82, 92, 93]

 To access the length of the array, you will use an attribute called length to retrieve the length of the calling array.
 This is called an attribute and not a method because it is a built-in property and it not calling on a method.
 Therefore, unlike the stringName.length(), the arrayName.length does not use any parentheses.

System.out.println(grades.length); //This would print out 5

The following lines of code would cause an error called ArrayIndexOutOfBoundsException

3
System.out.println(grades[grades.length]);
System.out.println(grades[-3]);
System.out.println(grades[1.5]);

Traversing an Array
 To traverse the contents of an array, we use a for loop to access each item in the array.
 The variable used in the for loop header is the index, and is usually called i
 Inside the for loop, we can either access or modify the contents of the array using the index

Traversing an Array to Display Contents Traversing an Array for Array Creation

int[] myArr = …; //creation not shown int[] myArr = new int[50];


//put all multiples of 2 into the array
for(int i = 0; i < myArr.length; i++) //starting at 0
{
System.out.println(myArr[i]); for(int i = 0; i < myArr.length; i++)
} {
myArr[i] = i * 2;
}

Practice
1) What is printed? 2) What is printed?

int[] values = {2, 7, 11, 4, 13, 8}; int[] values = {2, 7, 11, 4, 13, 8};
for(int i = 0; i < values.length; i++) for(int i = 0; i < values.length; i++)
{ {
if(values[i] % 2 == 0) if(i % 2 == 0)
System.out.print(values[i] + “ “); System.out.print(values[i] + “ “);
} }

The even elements in the array: 2 4 8 The elements of the even indexes: 2 11 13

3) What is printed? 4) What is printed?


4
String[] farm = {"horse", "cow", "pig", "goat", String[] farm = {"horse", "cow", "pig", "goat",
"chicken", "sheep"}; "chicken", "sheep"};
for(int i = 0; i < farm.length; i++) for(int i = farm.length - 1; i >= 0; i--)
{ {
if(farm[i].length() > 4) if(farm[i].substring(1,2).equals(“o”))
{ {
System.out.print(farm[i] + “ “); System.out.print(farm[i] + “ “);
} }
} }

The words that have a word length larger than 4: horse chicken sheep Starting at the last index, if the word’s second letter is an “o”, print it off:
goat cow horse

5) Finish the code so that the sum of the elements in the array is printed. 6) Finish the code so the sum of the odd elements in the array is printed.

int[] arr = …; //array elements are not shown int[] arr = …; //array elements are not shown
int sum = 0; int sum = 0;

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


{ {
sum += arr[i]; if(arr[i] % 2 == 1)
} {
sum += arr[i];
System.out.println("The sum is " + sum); }
}

System.out.println("The sum is " + sum);


7) What is the value of count after the code has executed? 8) What are the contents of the array after the code has been executed?
[0, 0, 0, 0, 0]
int count = 0; int[] mystery = new int[5]; [8, 0, 0, 0, 0]
int[] nums = {4, 8, 5, 11, 12, 10}; mystery[0] = 8;
[8, 10, 0, 0, 0]
for(int i = 0; i < nums.length – 1; i++) [8, 10, 2, 0, 0]
{ mystery[1] = 2 + mystery[0]; [8, 10, 2, 8, 0]
if(nums[i + 1] > nums[i]) [8, 24, 30, 6, 24]
mystery[2] = mystery[0] % 3;
count++;
} mystery[mystery[2] + 1] = mystery[0];
for(int i = mystery.length - 1; i > 0; i--)
count is counting how many elements have the number next in the array
larger than the current element. At the end, count will be 3. mystery[i] = mystery[i - 1] * 3;
Passing Arrays
5
 In the last unit, we discussed
o how primitive types (and Strings) are “pass by value”, meaning you pass a copy of the argument value to the method, so any changes made to the
variable in the method are not preserved
o how reference types pass the reference of the object, and therefore any changes made to the object in the method are preserved
 Arrays are a special type of object, and therefore behave like reference types; any changes made to an array that is passed as a parameter are preserved

public class ExampleOne { 40 70


stats 50
public static void main(String[] args) { 30 41 60 71
51
42 72
int[] stats = {30, 40, 50, 60, 70};
manipulate(stats); arr

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


System.out.print(stats[i] + " ");
} Console: 30 42 51 60 72
}

public static void manipulate(int[] arr) {


This method goes through each element
for(int i = 0; i < arr.length; i++){ and while the element is not evenly
divisible by 3, it adds 1 to it until it is. At
while(arr[i] % 3 != 0)
the end of this method, the contents are:
arr[i]++; [30, 42, 51, 60, 72]
}
}
}

6
Methods can also return arrays. What is printed when the following code is run?
otherArr gets assigned to newArr, therefore
public class ExampleTwo { otherArr = [false, true, false,
public static void main(String[] args) { true, false]
numbers never changed, so when we go through both
int[] numbers = {-10, 15, -20, 25, -30}; arrays
boolean[] otherArr = positives(numbers);
for(int i = 0; i < numbers.length; i++){ Console:
-10 false
System.out.println(numbers[i] + " " + otherArr[i]); 15 true
} -20 false
25 true
} -30 false

public static boolean[] positives(int[] arr) {


boolean[] newArr = new boolean[arr.length]; arr = [-10, 15, -20, 25, -30]
for(int i = 0; i < arr.length; i++){ A new array of boolean values is created that matches the
if(arr[i] > 0) length of the array that is passed
newArr[i] = true; newArr = [false, false, false, false, false]
}
The for loop goes through arr and checks if the element is a
return newArr;
positive number. If it is, the value gets changed to true.
}
} At the end of the loop:
newArr = [false, true, false, true, false]

Lesson 2: Searching Algorithm for Arrays


Objectives
7
 CON-2.K: Apply sequential/linear search algorithms to search for specific information in array.

Searching an Array
 Searching an array is doing exactly what it sounds like: we search an array for an element Binary search is discussed in
 In a linear search algorithm, we search an array for a specific algorithm by doing the following: Unit 7 & 10 and the sorting
algorithms will be discussed in
o starting at index 0, go up through the array one element at a time Unit 7 (selection and insertion) &
o check to see if the current index contains the element you are looking for 10 (merge sort)

o if it is, communicate the index that the element was found at


o if you look through the whole array and do not find the element, communicate an index that is not possible: 1
 This is similar to the String method .indexOf(“ “) which will return a 1 if the substring couldn’t be found.

Below are the steps for the linear search algorithm. In the space to the right, write the algorithm as a static method.

public static int linearSearch(String[] arr, String word)


1. The method will be passed two parameters: an
{
array to search and the value in the array you want
for(int i = 0; i < arr.length; i++)
to find. It will return the location of the value or -1
{
if the value is not found.
if(arr[i].equals(word))
{
2. Start at the beginning of the array and loop
return i;
through all the elements of the array.
}
}
3. Check each element to see if it is equal to the return -1;
value you are looking for. If it is, return that index. }

4. If you loop through the whole array and did not


find the value you were looking for, return a -1.

Practice

8
/** Returns the last index of a value
* Precondition: passed a non-empty array of integers and a value to find
*/

public static int indexOfLast(int[] values, int find)


{
Write a method called indexOfLast that int last = -1;
accepts an array of integer values and a value for(int i = 0; i < values.length; i++)
that you are searching the list for. The method {
returns the largest (last) index that the value is if(values[i] == find)
located at. {
last = i;
}
}
return last;
}

Lesson 3: Common Algorithms for Arrays


Objectives
 CON-2.I: For algorithms in the context of a particular specification that requires the use of array traversals: a. Identify standard algorithms. b. Modify
standard algorithms. c. Develop an algorithm.

Common Algorithms
 When we have an array of data, there are some common tasks we end up performing on it
 The algorithms we will create on the next few pages are a snapshot of those common tasks
 These algorithms happen so frequently, you will want to make sure you understand how they accomplish their task
 Do you have to memorize them? No. BUT you’ll use them so often it is helpful to know the best way to accomplish these tasks

Algorithm #1: Determine a minimum or maximum value from an array of integers.

Write a method called max /** Returns the index of the largest number
9
* Precondition: passed a non-empty array of integers
*/

public static int max(int[] arr){


int max = arr[0];
int maxIndex = 0;
that returns the index of the
for(int i = 1; i < arr.length; i++){
largest number (maximum)
in a passed array of if(max < arr[i]){
integers. max = arr[i];
maxIndex = i;
}
}
return maxIndex;
}

Algorithm #2: Compute a sum from an array of integers

/** Returns the sum of the elements in an array


* Precondition: passed a non-empty array of integers
*/

public static int sum(int[] arr){


int sum = 0;
Write a method called sum for(int i = 0; i < arr.length; i++){
that returns the sum of the sum += arr[i];
elements in an array that is }
passed to the method. return sum;
1. Keep track of the sum
} 2. Traverse the array
3. Add the current element to sum
4. Return the sum

Algorithm #3: Determine if at least one element has a particular property

10
/** Returns true if there is at least one negative in an array of ints
* Precondition: passed a non-empty array of integers
*/

public static boolean anyNegatives(int[] arr){


Write a method called for(int i = 0; i < arr.length; i++){
anyNegatives that is if(arr[i] < 0){
passed an array of integer return true;
values and will return true }
if there is at least one
}
negative value.
return false;
}

Algorithm #4: Determine if all elements have a particular property

/** Returns true if there is at least one negative in an array of ints


* Precondition: passed a non-empty array of integers
*/

public static boolean negativeValues(int[] arr){


Write a method called for(int i = 0; i < arr.length; i++){
negativeArray that is
if(arr[i] > 0){
passed an array of integer
values and will return true return false; 1. Traverse the array
if there are all negative } 2. Check if the current element is
values. } positive
return true; 3. Return false, since a positive
was found
}
4. Return true after the loop if a
positive was never found

Algorithm #5: Determine the number of elements meeting specific criteria

11
/** Returns the number of elements that are divisible by 3
* Precondition: passed a non-empty array of integers
*/

public static int threeMultiples(int[] arr){


int count = 0;
for(int i = 0; i < arr.length; i++){
Write a method called if(arr[i] % 3 == 0){
threeMultiples that count++; The following common algorithms will be
returns the number of } covered in the homework assignment & quiz
elements in an array that are } review following this lesson:
evenly divisible by 3. 1. Have a variable to keep track of
return count;  Determine if all elements have a
count
} 2. Traverse the array particular property
3. Check if the current element is  Access all consecutive pairs of
evenly divisible by 3 elements
4. If it is, add one to count  Determine the presence or absence of
5. Return the count duplicate elements

Swapping Algorithm
To swap two elements of the array, a simple algorithm can be followed:
1. Store the value of the first element in a temporary variable
2. Assign the value of the second element to the first element
3. Assign the value of the temporary variable to the second element

Consider the data set of the String array called animals:

String[] animals = {“Dog”, “Goat”, “Cat”, “T-Rex”, “Duck”};


//Write code to swap “Goat” and “Duck”

String temp = animals[1];


animals[1] = animals[4];
animals[4] = temp;

Algorithm #6: Shift or rotate elements left or right

12
/** Shifts all the elements of an array to the left
* Precondition: passed a non-empty array of integers
*/

Write a method called public static void shiftLeft(int[] arr){


shiftLeft that will take int temp = arr[0];
an array of integers and shift for(int i = 0; i < arr.length - 1; i++){
all the elements to the left. arr[i] = arr[i + 1];
The element at the beginning }
of the array should move to arr[arr.length – 1] = temp;
the end of the array.
}

Algorithm #7: Reverse the order of the elements

/** Reverses all the elements in the array


* Precondition: passed a non-empty array of integers
*/

public static void reverse(int[] arr){


Write a method called
for(int i = 0; i < arr.length / 2 ; i++)
reverse that will take an
{
array of integers and reverse
the contents of the array. int middleEnd = arr.length – i – 1; //index of element in end half
int temp = list[i];
For example, if our array is list[i] = list[middleEnd];
[3, 6, 7, 10], the reversed list[middleEnd] = temp;
array will be [10, 7, 6, 3]. } 1. Traverse the beginning half the array
} 2. Find the corresponding index in the end
half of the array
3. Use the swapping algorithm to swap
these two elements

Lesson 4: The Enhanced For Loop


Objectives
13
 VAR-2.C Traverse the elements in a 1D array object using an enhanced for loop.

For Each Loop


 Introducing a new type of loop: the for each loop (also called the enhanced for loop)
 This loop uses a modified syntax to traverse through arrays, or eventually, ArrayLists
 The syntax looks like:

for(type var : array)


{
statements using var;
}

 When reading this code, we say “for each var in array, do this with var”
 For each iteration of the loop, the variable var will reference the current element in the array. When the loop repeats, the variable var will reference the
next element in the array, and so on.

Printing the contents of an array with a for loop Printing the contents of an array with an enhanced for loop

int[] arr = {2, 5, 3, 7, 9}; int[] arr = {2, 5, 3, 7, 9};


for (int i = 0; i < arr.length; i++) for (int n : arr)
{ {
System.out.print(arr[i] + " "); System.out.println(n + " ");
} }

 The for loop says “do something a certain number of times”


 The for-each loop says “do this with every element in the list”

Practice: Write a for-each loop to accomplish the following tasks.

14
In an array of integers called numList, print off the odd elements. In an array of Strings called words, print off the first letter of each word.

for(int num : numList)


{
for(String value : words)
if(num % 2 == 1)
{
{
System.out.println(value.substring(0,1));
System.out.println(num);
}
}
}

 While any for-each loop can be written as a for loop, the opposite is not true.
 There are some limitations when it comes to a for-each loop in an array

For example, you cannot modify the contents of an array in a for-each loop:

While the code below is correct and will run, the variable num is a local
variable to the loop, and gets assigned the value of the element in the list. To modify the contents of the array, you would need to use a for loop
The list does not get modified, just the variable num does.
int[] arr = {2, 5, 3, 7, 9}; int[] arr = {2, 5, 3, 7, 9};

for (int num : arr) for(int i = 0; i < arr.length; i++)


{ {
num++; arr[i]++;
System.out.print(num + " "); System.out.print(arr[i]);
} }
System.out.print("\n");
Console: for (int num : arr) Console:
for (int num : arr) {
{ 3 6 4 8 10 System.out.print(num + " "); 3 6 4 8 10
System.out.print(num + " "); }
} 2 5 3 7 9 3 6 4 8 10

The for-each loop also has many limitations when it comes to ArrayLists, which will be discussed in Unit 7.
Lesson 5: Arrays of Objects
Objectives
15
 VAR-2.A: Represent collections of related primitive or object reference data using one-dimensional (1D) array objects

Arrays of Objects
 An array can hold any data type, including objects!
 When visualizing an array of objects, lets think back to our Dog class from earlier units.

Creating an Array of Objects


 If we wanted to create an array of dog objects, we would use the following syntax:

null null null null


Dog[] doggieList = new Dog[4];

doggieList

 This creates an array of 4 Dog references. Right now, however, the Dog objects have not been created so each value has a null reference in it.
 To create the Dog, we will still have to call on a constructor, and we need to do this for each Dog element in the array:

doggieList
doggieList[0] = new Dog();
doggieList[1] = new Dog(“Fido”, 3, true);
doggieList[2] = new Dog(“Bubbles”, 10);
doggieList[3] = new Dog(“Mallory”, 2, false);
Unknown Fido Bubbles Mallory
0 3 10 2
true true true false

 Another way to create an array of objects is to create the array and call on the constructors in one line:

Dog[] otherList = {new Dog(), new Dog(“Hulk”, 2), new Dog(“Thor”, 8, false)}

Using an Array of Objects


Now we can use all the methods available in our Dog class on our Dog objects.

16
What do the following lines of code print to the console?

System.out.println(doggieList[1].getName());
Console:
doggieList[0].setName(“Peaches”);
Fido
System.out.println(doggieList[0].getName());
for(int i = 0; i < doggieList.length; i++){ Peaches

doggieList[i].setAge(doggieList[i].getAge() + 1); 1 4 11 3
}
for(Dog puppy : doggieList){
System.out.print(puppy.getAge() + “ “);
}

17

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy