AP CSA 2.8 Exercise 1: Three Ways Round

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

Three Ways Round

for Loops. Write real Java, run it, and submit it to be graded against hidden test cases.

Why this one is worth doing

A for loop puts the start, the stop and the step on one line, which makes off by one errors easier to see and easier to make. Three loops here, each with a different bound.

What to write

  1. Read two integers, n and step.
  2. Using a for loop, print every number from 1 to n on its own line.
  3. Then print the sum of the squares of 1 through n on one line.
  4. Then, counting DOWN from n to 1 with a step of the given size, print each value you land on, one per line.
  5. Assume n is at least 1 and step is at least 1.

Your program reads

Two integers on separate lines: n, then step.

Your program prints

n lines counting up, then the sum of squares, then the values counted down by step.

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
2
Example 1 output
1
2
3
4
5
55
5
3
1
Example 2 input
1
1
Example 2 output
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

i <= n runs n times when i starts at 1. i < n runs n - 1 times, which is the off by one this exercise is looking for.

Hint 2

The countdown starts at n, tests i >= 1, and subtracts step. It will usually not land exactly on 1, and that is correct.

Hint 3

The counter declared inside the for header disappears at the closing brace, so all three loops can reuse the name i.

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]