AP CSA Adjacent Elements

Adjacent Element Patterns in AP CSA

Many array algorithms compare or combine neighboring elements — arr[i] and arr[i+1]. The critical detail: your loop must stop one short of the last index to avoid an ArrayIndexOutOfBoundsException.

The Pattern

// Loop condition: i < arr.length - 1 (NOT i < arr.length)
for (int i = 0; i < arr.length - 1; i++) {
    // Now safe to access arr[i] AND arr[i+1]
    if (arr[i] > arr[i + 1]) {
        System.out.println("Drop at index " + i);
    }
}

Common Adjacent-Element Tasks

Task Pattern
Find where array decreases arr[i] > arr[i+1]
Check if sorted If any arr[i] > arr[i+1], not sorted
Count adjacent equal pairs arr[i] == arr[i+1]
Sum of adjacent pairs arr[i] + arr[i+1]

📝 Practice Question 1

What is the correct loop condition when comparing arr[i] with arr[i+1] for an array of length n?

📝 Practice Question 2

What does the following method return when called with {2, 4, 3, 5, 5, 1}?

public static int mystery(int[] arr) {
    int count = 0;
    for (int i = 0; i < arr.length - 1; i++)
        if (arr[i] >= arr[i+1]) {
            count++;
        }
    return count;
}
✅ Exam Tip: Adjacent element questions are a staple of AP FRQs. The loop bound i < arr.length - 1 is the single most important thing to get right. Any other bound risks an exception or skipping the last pair.

Get in Touch

Whether you're a student, parent, or teacher — I'd love to hear from you.

Just want free AP CS resources?

Enter your email below and check the subscribe box — no message needed. Students get daily practice questions and study tips. Teachers get curriculum resources and teaching strategies.

Typically responds within 24 hours

Message Sent!

Thanks for reaching out. I'll get back to you within 24 hours.

🏫 Welcome, fellow educator!

I offer curriculum resources, practice materials, and study guides designed for AP CS teachers. Let me know what you're looking for — whether it's classroom materials, a guest speaker, or Teachers Pay Teachers resources.

Email

[email protected]

📚

Courses

AP CSA, CSP, & Cybersecurity

Response Time

Within 24 hours

Prefer email? Reach me directly at [email protected]