AP CSA 2.12 Exercise 1: Counting the Steps

Unit 2: Selection and Iteration · Lesson 2.12 · Exercise 1

Counting the Steps

Informal Run-Time Analysis. Write real Java, run it, and submit it to be graded against hidden test cases.

Why this one is worth doing

Run time analysis is counting, and counting is something a program can do to itself. Print the real step counts for three loop shapes and the growth rates stop being abstractions.

What to write

  1. Read one integer n, which is at least 1.
  2. Count and print how many times the body of a single loop from 1 to n runs.
  3. Count and print how many times the body of a nested loop, both from 1 to n, runs.
  4. Count and print how many times a loop that starts at n and halves each pass runs before reaching 0.
  5. Count and print how many times the body of a triangular nested loop runs, where the inner loop goes from 1 to the outer counter.

Your program reads

A single integer of at least 1.

Your program prints

Four counts, one per line: linear, quadratic, halving and triangular.

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
Example 1 output
5
25
3
15
Example 2 input
1
Example 2 output
1
1
1
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

The nested count should come out as exactly n times n. If it does not, one of the loops has the wrong bound.

Hint 2

Integer division is what makes the halving loop end: 1 / 2 is 0, so the last pass is the one that finishes it.

Hint 3

The triangular count is about half the nested one. Both are quadratic, which is why the exam calls them the same order of growth.

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]