# Have port declare closure of port or anything là gì

Swift and the Swift logo are trademarks of Apple Inc.

In the last lesson, we mentioned that you can use a variable for the index of an array. You can even do math with that index and have an arithmetic expression inside the [], like below.

// highScores array declaration int[] highScores = { 10, 9, 8, 8}; // use a variable for the index int index = 3; // modify array value at index highScores[index] = 11; // print array value at index System.out.println( highScores[index] ); System.out.println( highScores[index - 1] );

What does the code above print out? You can follow the code in this and look at the image depicting the array below.

Figure 1: Array with index variable

Coding Exercise

What do you think the following code will print out? First trace through it on paper keeping track of the array and the index variable. Then, run it to see if you were right. You can also follow it in the by clicking on the Show Code Lens button.

## 6.2.2. For Loop to Traverse Arrays

We can use iteration with a for loop to visit each element of an array. This is called traversing the array. Just start the index at 0 and loop while the index is less than the length of the array. Note that the variable i (short for index) is often used in loops as the loop counter variable and is used here to access each element of an array with its index.

Figure 2: For Loop Traversing Array

For example, here is a loop traversing the

int[] highScores = { 10, 9, 8, 11}; for (int i = 0; i < highScores.length; i++) {

``````System.out.println(  highScores[i] );
``````
}

1 array to print every score. Follow the code below in the .

int[] highScores = { 10, 9, 8, 11}; for (int i = 0; i < highScores.length; i++) {

``````System.out.println(  highScores[i] );
``````
}

Note

Using a variable as the index is a powerful data abstraction feature because it allows us to use loops with arrays where the loop counter variable is the index of the array! This allows our code to generalize to work for the whole array.

Coding Exercise

What do you think the following code will print out? First trace through it on paper keeping track of the array and the index variable. Then, run it to see if you were right. Try the Code Lens button. Then, try adding your name and a friend’s name to the array names and run the code again. Did the code work without changing the loop?

The following code demonstrates a loop that changes the values in an array. In this code, the array is passed as an argument to the static methods in the class. Arrays in Java are objects. The array variables are references to an address in memory. Since arrays can be very large, we do not want to copy them when we pass them into methods. When an array is passed as an argument to a method, the name of the array refers to its address in memory. Therefore, any changes to the array in the method will affect the original array. You can also try the code in the .

Coding Exercise

What does the following code print out? Trace through it keeping track of the array values and the output. Then run it to see if you’re right. Notice that in this code, the array is passed as an argument to the methods. You can also try the code in the with the Code Lens button.

Note

Arrays in Java are objects. When arrays are passed in as arguments to methods, any changes to the array in the method will affect the original array, since the array name is a reference value refering to the address of the array in memory.

The following method has the correct code to subtract amt from all the values in the array values, but the code is mixed up. Drag the blocks from the left into the correct order on the right. You will be told if any of the blocks are in the wrong order.

``````    public void subAll(int[] values, int amt)
``````
{

`````` for (int i = 0;
``````

``````    i < values.length;
``````

``````    i++)
``````

`````` {
``````

``````    values[i] = values[i] - amt;
``````

`````` } // end for loop
``````

} // end method

``````
``````
## 6.2.3. Looping From Back to Front

You don’t have to loop through an array from the front to the back. You can loop by starting at the back of the array and move toward the front during each time through the loop. In the example below, the method

int[] highScores = { 10, 9, 8, 11}; for (int i = 0; i < highScores.length; i++) {

``````System.out.println(  highScores[i] );
``````
}

2 returns the index of the last element in the array that is smaller than the given argument. The return statement inside the loop stops the execution of the loop and the method and returns the index that is found immediately back to the main method. It returns -1 if there is no number in the array that is smaller than the given number.

Coding Exercise

What does the following code print out? Notice that the array and the target are passed in as arguments to the getIndexOfLastElementSmallerThanTarget method. Trace through it keeping track of the array values and the output. Then run it to see if you’re right. You can also try the code in the with the Code Lens button. Can you add another method that finds the index of the last element greater than the target instead of smaller than the target and have main print out a test of it? Call this method getIndexOfLastElementGreaterThanTarget and give it 2 arguments and a return value like the method below.

6-2-6: Given the following code segment (which is identical to the method above) what will be returned when you execute:

int[] highScores = { 10, 9, 8, 11}; for (int i = 0; i < highScores.length; i++) {

``````System.out.println(  highScores[i] );
``````
}

3;

private int[ ] values = {-20, -15, 2, 8, 16, 33}; public static int getIndexOfLastElementSmallerThanTarget(int[ ] values, int compare) { for (int i = values.length - 1; i >=0; i--) {

``````  if (values[i] < compare)
return i;
``````
} return -1; // to show none found }

• -1
• The method will only return -1 if no value in the array is less than the passed value.
• -15
• The method returns the index of the first item in the array that is less than the value, not the value.
• 1
• Since the method loops from the back towards the front -15 is the last value in the array that is less than -13 and it is at index 1.
• You will get an out of bounds error.
• No, the method correctly starts the index at values.length - 1 and continues as long as i is greater than or equal to 0.

6-2-7: Given the following code segment (which is not quite identical to the method above) what will be returned when you execute:

int[] highScores = { 10, 9, 8, 11}; for (int i = 0; i < highScores.length; i++) {

``````System.out.println(  highScores[i] );
``````
}

4;

int[ ] values = {-20, -15, 2, 8, 16, 33}; public static int getIndexOfLastElementSmallerThanTarget(int[] values, int compare) { for (int i = values.length; i >=0; i--) {

``````  if (values[i] < compare)
return i;
``````
} return -1; // to show none found }

• -1
• The method will only return -1 if no value in the array is less than the passed value.
• 1
• Check the starting index. Is it correct?
• 2
• Check the starting index. Is it correct?
• You will get an out of bounds error.
• You can not start the index at the length of the array. You must start at the length of the array minus one. This is a common mistake.

## 6.2.4. Looping through Part of an Array

You don’t have to loop through all of the elements of an array. You can loop through just some of the elements of an array using a for loop. The following code doubles the first five elements in an array. Notice that it uses a complex conditional (

int[] highScores = { 10, 9, 8, 11}; for (int i = 0; i < highScores.length; i++) {

``````System.out.println(  highScores[i] );
``````
}

1. on line 14 to make sure that the loop doesn’t go beyond the length of the array, because if you had an array that had less than 5 elements, you wouldn’t want the code to try to double the 5th element which doesn’t exist! Notice that in this code, the array is a private instance variable of the class ArrayWorker. It is created in the constructor and changed or accessed by the methods.

What will the following code print out? Can you write a similar method called tripleFirstFour() that triples the first 4 elements of the array? Make sure you test it in main.

Coding Exercise

You can even start in the middle and loop through the rest of the array.

Does this work for arrays that have an even number of elements? Does it work for arrays that have an odd number of elements? Modify the main code below to test with both arrays with an even number of items and an odd number.

6-2-10: Given the following values of a and the method doubleLast what will the values of a be after you execute: doubleLast()?

private int[ ] a = {-20, -15, 2, 8, 16, 33}; public void doubleLast() { for (int i = a.length / 2; i < a.length; i++) {

``````  a[i] = a[i] * 2;
``````
} }

• {-40, -30, 4, 16, 32, 66}
• This would true if it looped through the whole array. Does it?
• {-40, -30, 4, 8, 16, 32}
• This would be true if it looped from the beginning to the middle. Does it?
• {-20, -15, 2, 16, 32, 66}
• It loops from the middle to the end doubling each value. Since there are 6 elements it will start at index 3.
• {-20, -15, 2, 8, 16, 33}
• This would be true if array elements didn't change, but they do.

6-2-11: Given the following values of a and the method mystery what will the values of a be after you execute: mystery()?

private int[ ] a = {-20, -15, 2, 8, 16, 33}; public void mystery() { for (int i = 0; i < a.length/2; i+=2) {

``````  a[i] = a[i] * 2;
``````
} }

• {-40, -30, 4, 16, 32, 66}
• This would true if it looped through the whole array and doubled each. Does it?
• {-40, -30, 4, 8, 16, 33}
• This would be true if it looped from the beginning to the middle and doubled each. Does it?
• {-20, -15, 2, 16, 32, 66}
• This would be true if it looped from the middle to the end and doubled each. Does it?
• {-40, -15, 4, 8, 16, 33}
• This loops from the beginning to the middle and doubles every other element (i+=2 is the same as i = i + 2).
• {-40, -15, 4, 8, 32, 33}
• This would be true if it looped through the whole array and doubled every other element. Does it?

The following program has the correct code to reverse the elements in an array, a, but the code is mixed up. Drag the blocks from the left into the correct order on the right. You will be told if any of the blocks are in the wrong order.

``````    public static void reverse(int[] a)
``````
{

int temp = 0; int half = a.length / 2; int max = a.length - 1;

for (int i = 0; i < half; i++) {

`````` temp = a[i];
``````

`````` a[i] = a[max - i];
``````

`````` a[max - i] = temp;
``````

} // end for

} // end method

``````
``````
The following program has the correct code to return the average of the first 3 items in the array a, but the code is mixed up. Drag the blocks from the left into the correct order on the right. You will be told if any of the blocks are in the wrong order or are indented incorrectly.

``````    public static double avg3(int[] a)
``````
{

double total = 0;

for (int i = 0; i < a.length && i < 3; i++) {

``````total = total + a[i];
``````

} // end method

``````
``````
## 6.2.5. Common Errors When Looping Through an Array

When processing all array elements, be careful to start at the first index which is

int[] highScores = { 10, 9, 8, 11}; for (int i = 0; i < highScores.length; i++) {

``````System.out.println(  highScores[i] );
``````
}

6 and end at the last index. Usually loops are written so that the index starts at 0 and continues while the index is less than

int[] highScores = { 10, 9, 8, 11}; for (int i = 0; i < highScores.length; i++) {

``````System.out.println(  highScores[i] );
``````
}

7 since (

int[] highScores = { 10, 9, 8, 11}; for (int i = 0; i < highScores.length; i++) {

``````System.out.println(  highScores[i] );
``````
}

1. is the index for the last element in the array. Make sure you do not use

int[] highScores = { 10, 9, 8, 11}; for (int i = 0; i < highScores.length; i++) {

``````System.out.println(  highScores[i] );
``````
}

``````    public void subAll(int[] values, int amt)
``````
{

`````` for (int i = 0;
``````

``````    i < values.length;
``````

``````    i++)
``````

`````` {
``````

``````    values[i] = values[i] - amt;
``````

`````` } // end for loop
``````

} // end method

``````
``````
0! If the index is less than 0 or greater than (

int[] highScores = { 10, 9, 8, 11}; for (int i = 0; i < highScores.length; i++) {

``````System.out.println(  highScores[i] );
``````
}

8), an ArrayIndexOutOfBoundsException will be thrown. Off by one errors, where you go off the array by 1 element, are easy to make when traversing an array which result in an ArrayIndexOutOfBoundsException being thrown.

6-2-14: Which of the following loop headers will cause an ArrayIndexOutOfBounds error while traversing the array scores?

• for (int i = 0; i < scores.length; i++)
• This loop will traverse the complete array.
• for (int i = 1; i < scores.length; i++)
• This loop will not cause an error even though it will not visit the element at index 0.
• for (int i = 0; i <= scores.length; i++)
• The index cannot be equal to scores.length, since (scores.length - 1) is the index of the last element.
• for (int i = 0; scores.length > i; i++)
• Although the ending condition looks strange, (scores.length > i) is equivalent to (i < scores.length).
• for (int i = scores.length - 1; i >= 0; i++)
• This will cause an error because i++ will continue to increment the index past the end of the array. It should be replaced with i– to avoid this error.

Coding Exercise

The following code has an ArrayIndexOutOfBoundsException. It has 2 common off-by-one errors in the loop. Can you fix it and make the loop print out all the scores?

Be careful not to jump out of loop too early when you are looking for a value in an array. The method below uses return statements to stop the execution of the method and return a value to the method that called this method. However, you must be careful not to stop the loop too soon.

Coding Exercise

What is wrong with the code below? The first time through the loop it will start with the element at index 0 and check if the item at the array index equals the passed target string. If they have the same characters in the same order it will return 0, otherwise it will return -1. But, it has only processed one element of the array. How would you fix the code to work correctly (process all array elements before returning)?

6-2-17: Given the following code segment, which of the following will cause an infinite loop? Assume that

``````    public void subAll(int[] values, int amt)
``````
{

`````` for (int i = 0;
``````

``````    i < values.length;
``````

``````    i++)
``````

`````` {
``````

``````    values[i] = values[i] - amt;
``````

`````` } // end for loop
``````

} // end method

``````
``````
2 is an int variable initialized to be greater than zero and that

``````    public void subAll(int[] values, int amt)
``````
{

`````` for (int i = 0;
``````

``````    i < values.length;
``````

``````    i++)
``````

`````` {
``````

``````    values[i] = values[i] - amt;
``````

`````` } // end for loop
``````

} // end method

``````
``````
3 is an array of integers.

for ( int k = 0; k < a.length; k++ ) { while ( a[ k ] < temp ) {

``````  a[ k ] *= 2;
``````
} }

• The values don't matter this will always cause an infinite loop.
• An infinite loop will not always occur in this code segment.
• Whenever a includes a value that is less than or equal to zero.
• When a contains a value that is less than or equal to zero then multiplying that value by 2 will never make the result larger than the temp value (which was set to some value > 0), so an infinite loop will occur.
• Whenever a has values larger then temp.
• Values larger then temp will not cause an infinite loop.
• When all values in a are larger than temp.
• Values larger then temp will not cause an infinite loop.
• Whenever a includes a value equal to temp.
• Values equal to temp will not cause the infinite loop.

## 6.2.6. Programming Challenge : SpellChecker

In this challenge, you will use an array of English words from a dictionary file to see if a given word is spelled correctly. We encourage you to work in pairs for this challenge. Make sure you have done the last coding exercise above which will help you with this challenge.

This challenge includes a dictionary file of 10,000 English words which is read into the array dictionary for you. You could use this replit code instead that has an even bigger dictionary of English words and lets you do input with your spell checker. If you use repl, copy in the link for your repl in the Active Code window below to turn it in. If you are interested in how to read in files using Java, there is an optional input files lesson at the end of Unit 7.

1. Write a
``````    public void subAll(int[] values, int amt)
``````
{
`````` for (int i = 0;
``````

``````    i < values.length;
``````

``````    i++)
``````

`````` {
``````

``````    values[i] = values[i] - amt;
``````

`````` } // end for loop
``````

} // end method
``````
``````
4 method that prints out the first 10 words of the dictionary array. Do not print out the whole array of 10,000 words!
2. Write a
``````    public void subAll(int[] values, int amt)
``````
{
`````` for (int i = 0;
``````

``````    i < values.length;
``````

``````    i++)
``````

`````` {
``````

``````    values[i] = values[i] - amt;
``````

`````` } // end for loop
``````

} // end method
``````
``````
5 method that takes a word as a parameter and returns true if it is in the dictionary array. It should return false if it is not found (When can you tell that you have not found a word in the dictionary?). Test your code below by changing the word sent to the spellcheck() method in main. This algorithm is called a linear search where we step through the array one element at a time (here the dictionary one word at a time) looking for a certain element.
3. Optional Challenge: Write a method
``````    public void subAll(int[] values, int amt)
``````
{
`````` for (int i = 0;
``````

``````    i < values.length;
``````

``````    i++)
``````

`````` {
``````

``````    values[i] = values[i] - amt;
``````

`````` } // end for loop
``````

} // end method

``````
``````
``````    public void subAll(int[] values, int amt)
``````
{

`````` for (int i = 0;
``````

``````    i < values.length;
``````

``````    i++)
``````

`````` {
``````

``````    values[i] = values[i] - amt;
``````

`````` } // end for loop
``````

} // end method

``````
``````
7 of letters in the
``````    public void subAll(int[] values, int amt)
``````
{

`````` for (int i = 0;
``````

``````    i < values.length;
``````

``````    i++)
``````

`````` {
``````

``````    values[i] = values[i] - amt;
``````

`````` } // end for loop
``````

} // end method

``````
``````
8 array. Your method should take a parameter for the
``````    public void subAll(int[] values, int amt)
``````
{

`````` for (int i = 0;
``````

``````    i < values.length;
``````

``````    i++)
``````

`````` {
``````

``````    values[i] = values[i] - amt;
``````

`````` } // end for loop
``````

} // end method

``````
``````
9 as a
``````    public void subAll(int[] values, int amt)
``````
{

`````` for (int i = 0;
``````

``````    i < values.length;
``````

``````    i++)
``````

`````` {
``````

``````    values[i] = values[i] - amt;
``````

`````` } // end for loop
``````

} // end method

``````
``````
7. You could use the Java String startsWith() method here if you’d like to, or use private int[ ] values = {-20, -15, 2, 8, 16, 33}; public static int getIndexOfLastElementSmallerThanTarget(int[ ] values, int compare) { for (int i = values.length - 1; i >=0; i--) {
``````  if (values[i] < compare)
return i;
``````
} return -1; // to show none found } 1 to see if the
``````    public void subAll(int[] values, int amt)
``````
{

`````` for (int i = 0;
``````

``````    i < values.length;
``````

``````    i++)
``````

`````` {
``````

``````    values[i] = values[i] - amt;
``````

`````` } // end for loop
``````

} // end method
``````
``````
9 is at index 0 of the string. This is not autograded.

Data file:

private int[ ] values = {-20, -15, 2, 8, 16, 33}; public static int getIndexOfLastElementSmallerThanTarget(int[ ] values, int compare) { for (int i = values.length - 1; i >=0; i--) {

``````  if (values[i] < compare)
return i;
``````
} return -1; // to show none found }

3

int[] highScores = { 10, 9, 8, 11}; for (int i = 0; i < highScores.length; i++) {

``````System.out.println(  highScores[i] );
``````
}

0

Write print10 and spellcheck methods using for loops. Spellchek should take a word as a parameter and return true if it is in the dictionary array. Return false if it is not found.

## 6.2.8. Summary

• Iteration (loops) can be used to access all the elements in an array, traversing the array.
• Traversing an array with an indexed for loop or while loop requires elements to be accessed using their indices.
• Since the index for an array starts at 0 and end at the number of elements − 1, “off by one” errors are easy to make when traversing an array, resulting in an ArrayIndexOutOfBoundsException being thrown.

## 6.2.9. Arrays Game

Try the game below to practice loops with arrays. Click on Arrays and then check on Loops and click on the elements of the * array that would be printed out by the given code. If you’re stuck, check on Labels to see the indices. We encourage you to work in pairs and see how high a score you can get.