π4.4: Array Traversals
Table of Contents
π This page is a condensed version of CSAwesome Topic 4.4
Array Traversals
In this lesson, we will learn how to traverse an array using a loop. Traversing an array means visiting each element of the array. We can use a loop to visit each element of an array and perform some operation on it.
Index Variables
You can use a variable for the index of an array. You can even use arithmetic expressions inside the square brackets []
.
int[] highScores = { 10, 9, 8, 8 };
int index = 3;
highScores[index] = 11;
System.out.println(highScores[index]);
System.out.println(highScores[index - 1]);
Traversing with a For Loop
int[] nums = { 5, 10, 15, 20, 25 };
for (int i = 0; i < nums.length; i++) {
System.out.println(nums[i]);
}
Traversing in Reverse
for (int i = nums.length - 1; i >= 0; i--) {
System.out.println(nums[i]);
}
Enhanced For Loop (For-Each)
for (int value : nums) {
System.out.println(value);
}
Advantages: Shorter and easier to read when you only need to access elements. Limitations: Cannot modify array elements directly.
Traversing Arrays of Objects
You can traverse arrays of objects with either an indexed for loop or an enhanced for loop.
Example β Student Array Search:
-
Create a
findAndPrint(String name)
method that:- Uses an enhanced for loop to find a matching student by name.
- Prints that studentβs info.
-
Call it from
main
to test.
public class StudentArray {
private Student[] array;
public StudentArray(int size) {
array = new Student[size];
}
public void add(int i, Student s) {
array[i] = s;
}
public void print() {
for (Student s : array) {
System.out.println(s);
}
}
public static void main(String[] args) {
StudentArray roster = new StudentArray(3);
roster.add(0, new Student("Skyler", "skyler@sky.com", 123456));
roster.add(1, new Student("Ayanna", "ayanna@gmail.com", 789012));
roster.add(2, new Student("Dakota", "dak@gmail.com", 112233));
roster.print();
}
}
class Student {
private String name, email;
private int id;
public Student(String n, String e, int i) {
name = n;
email = e;
id = i;
}
public String getName() { return name; }
public String getEmail() { return email; }
public int getId() { return id; }
public String toString() {
return id + ": " + name + ", " + email;
}
}
Coding Challenge: Spell Checker
- Write
print10()
to print the first 10 words of thedictionary
array. - Write
spellcheck(String word)
to returntrue
if the word is in the dictionary, otherwisefalse
. - (Optional) Write
printStartsWith(String firstLetters)
to print all dictionary words that start with given letters.
import java.io.*;
import java.nio.file.*;
import java.util.*;
public class SpellChecker {
private String[] dictionary = new String[10000];
public void print10() { /* your code */ }
public boolean spellcheck(String word) { /* your code */ }
public SpellChecker() throws IOException {
List<String> lines = Files.readAllLines(Paths.get("dictionary.txt"));
dictionary = lines.toArray(dictionary);
}
public static void main(String[] args) throws IOException {
SpellChecker checker = new SpellChecker();
// checker.print10();
// System.out.println(checker.spellcheck("cat"));
}
}
Community Challenge: Array Loop
- Copy your class from Lesson 4.3.
- Create an array of 3 objects of your class.
- Initialize them using your constructor.
- Write a loop to print each object.
Summary
- (AP 4.4.A.1) Traversing an array means visiting each element in order.
- (AP 4.4.A.2) Indexed loops require using element indices.
- (AP 4.4.A.3) Enhanced for loop variables store copies of elements.
- (AP 4.4.A.4) Assigning to an enhanced loop variable does not change the array.
- (AP 4.4.A.5) You can change object attributes in arrays using methods inside an enhanced for loop.
Arrays Game
Play the Arrays Game to practice array traversal.
Acknowledgement
Content on this page is adapted from Runestone Academy - Barb Ericson, Beryl Hoffman, Peter Seibel.