AP CSA 2.1 Exercise 1: Choosing Without an if

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

Choosing Without an if

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

Why this one is worth doing

Selection and repetition are ideas before they are keywords. This exercise makes a real choice and does a real repetition without using an if or a loop, so the ideas arrive before the syntax does.

What to write

  1. Read three integers: a, b and c.
  2. Print the largest of the three using Math.max, which selects without an if statement.
  3. Print the smallest using Math.min.
  4. Print the middle value, which is the total minus the largest minus the smallest.
  5. Read one more integer n, then print the sum of every whole number from 1 to n using the closed form n * (n + 1) / 2, which does a repetition without a loop.

Your program reads

Four integers on separate lines: a, b, c, then n.

Your program prints

Four lines: the largest, the smallest, the middle value and the sum from 1 to n.

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
4
9
2
5
Example 1 output
9
2
4
15
Example 2 input
7
7
7
1
Example 2 output
7
7
7
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

Math.max takes two arguments, so three values need two calls: Math.max(a, Math.max(b, c)).

Hint 2

The middle value trick works even when two of the three are equal. Try it on 5, 5, 2 by hand and see.

Hint 3

n * (n + 1) is always even, so the / 2 is exact and integer division loses nothing here.

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]