AP CSA 4.5 Exercise 1: Four Standard Algorithms

Unit 4: Data Collections · Lesson 4.5 · Exercise 1

Four Standard Algorithms

Algorithms with Arrays. Write real Java, run it, and submit it to be graded against hidden test cases.

Why this one is worth doing

These four turn up on the exam in some form every year. Writing them once from an empty editor is worth more than reading them ten times.

What to write

  1. Read an integer count, then that many integers into an array.
  2. Print the sum of all the elements.
  3. Print the average as a double, so a whole number still shows a decimal point.
  4. Print how many elements are strictly greater than that average.
  5. Print true when the array is in non decreasing order, and false otherwise.
  6. Print the number of pairs of neighbouring elements that are equal.

Your program reads

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

Your program prints

Five lines: the sum, the average, the count above average, the sorted check and the equal neighbour count.

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
4.6
2
false
0
Example 2 input
4
1 2 2 5
Example 2 output
10
2.5
1
true
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

Cast the sum to double before dividing, or the average of 7 and 2 comes out as 4.0 instead of 4.5.

Hint 2

A neighbour comparison starts at i = 1 and looks back at i - 1, so it never reads past either end.

Hint 3

A one element array is sorted and has zero equal pairs. The loop simply does not run, which is the right answer.

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]