AP CSA 4.2 Exercise 1: For Each, Not For i

Unit 4: Data Collections · Lesson 4.2 · Exercise 1

For Each, Not For i

Introduction to Using Data Sets. Write real Java, run it, and submit it to be graded against hidden test cases.

Why this one is worth doing

The enhanced for loop hands you the values and never the positions. That makes it the right tool for a total and the wrong tool the moment you need to know where you are, which is the distinction this exercise is built around.

What to write

  1. The array is built for you from the input. Do not change that part.
  2. Using an ENHANCED for loop, print the sum of the values.
  3. Using an enhanced for loop, print how many of them are odd.
  4. Using an enhanced for loop, print the largest value.
  5. On the last line print the number of values, which the array itself can tell you.

Your program reads

An integer count, then that many integers.

Your program prints

Four lines: the sum, the count of odd values, the largest value and how many values there were.

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
4 7 2 9 1
Example 1 output
23
3
9
5
Example 2 input
1
6
Example 2 output
6
0
6
1

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

for (int value : data) reads every element in order. There is no i, and you do not need one for any of these three answers.

Hint 2

data.length is a field, not a method, so there are no parentheses after it.

Hint 3

A negative odd number is still odd. value % 2 != 0 is true for -3, while value % 2 == 1 is not.

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]