AP CSA 4.3 Exercise 1: Build It, Index It

Unit 4: Data Collections · Lesson 4.3 · Exercise 1

Build It, Index It

Array Creation and Access. Write real Java, run it, and submit it to be graded against hidden test cases.

Why this one is worth doing

An array of length n has indexes 0 through n minus 1, and asking for index n is the single most common runtime error in this unit. Two of the lines here are about the ends of the array for that reason.

What to write

  1. Read an integer count, then create an int array of that length.
  2. Read that many values into the array, in order.
  3. Print the length of the array.
  4. Print the FIRST element, then the LAST element, each on its own line.
  5. Print the element at the middle index, which is the length divided by 2 using integer division.
  6. Print the sum of the first and last elements.

Your program reads

An integer count of at least 1, then that many integers.

Your program prints

Five lines: the length, the first element, the last element, the middle element and the sum of the ends.

Worked examples

These are the cases you can see. There are more you cannot, and they use different values, so an answer that prints these numbers as constants will fail.

Example 1 input
5
10 20 30 40 50
Example 1 output
5
10
50
30
60
Example 2 input
1
7
Example 2 output
1
7
7
7
14

Your answer

Main.java

Input for the Run button

Run sends whatever is in the input box below. Submitting runs your program against every test case, including hidden ones with different input.


  

  

Stuck?

Hint 1

The last index is length - 1. data[data.length] is one past the end and throws ArrayIndexOutOfBoundsException.

Hint 2

new int[count] fills the array with zeros. Your loop is what puts the real values in.

Hint 3

For an array of length 5 the middle index is 2, which has two elements on each side. For length 4 it is 2, which is the right hand middle.

Where to go next

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]