📚

All Subjects

>

💻

AP Comp Sci A

>

⌚️

Unit 6

# 6.2 Traversing Arrays Peter Cao Caroline Koffke

### AP Computer Science A💻

Bookmarked 2.4k • 93 resources
See Units

## What is Traversing?

Traversing an array means to access every value in the array. To do this, we need to use a loop, and we most often use a for loop. To do so, we use the following:
```for (int i = 0; i < array.length; i++) { do something with array[i] } ```
Here is an example where we use a constructor to make a copy of arrayOne from the previous section:
```int[] arrayTwo = new int { for (int i = 0; i < array.length; i++) { arrayTwo[i] = i + 1; } } ```
Using regular for loops, we can either access array elements or manipulate them as above.
Sometimes, we want to go in reverse, from the end of the array to the beginning. This requires a change to the for loop condition to the following:
```for (int i = array.length - 1; i >= 0; i--) { do something with array[i] } ```
Other times we don't want to traverse through all elements in the array, but only starting from the second element to the end. From this we start at index i = 1 and end at i = array.length - 1. Perhaps we want to traverse only through the first n elements (assume n is smaller than array.length - 1). For this, we start at index i = 0 and end at i = n - 1. Using this, we can combine these two to traverse through any subsection of this array.
Using this for loop traversal, we can modify every value in the array. For example, this is a method that doubles every element in the array.
```/** Doubles each element of the array */ public static void doubleArray(int[] array) { for (int i = 0; i < array.length; i++) { array[i] *= 2; // doubles each individual element } } ```
This can be read as "for all indices i between 0 to array.length - 1, we find the array element at index i and double it." This is the same as what is done with other for loop traversals of this type.

Thousands of students are studying with us for the AP Computer Science A exam.
#####   Studying with Hours = the ultimate focus mode
Start a free study session
##### 🔍 Are you ready for college apps?
Take this quiz and find out!
Start Quiz
Browse Study Guides By Unit
🙏Exam Reviews
🖱Unit 10: Recursion
Unit 1: Primitive Types
📱Unit 2: Using Objects
🖥Unit 3: Boolean Expressions and if Statements
🕹Unit 4: Iteration
⚙️Unit 5: Writing Classes
⌚️Unit 6: Array
💾Unit 7: ArrayList
💻Unit 8: 2D Array
🖲Unit 9: Inheritance
#####  FREE AP comp sci a Survival Pack + Cram Chart PDF  