AP CSA 4.12 Exercise 1: Across, Down, Diagonal

Unit 4: Data Collections · Lesson 4.12 · Exercise 1

Across, Down, Diagonal

Traversing 2D Arrays. Write real Java, run it, and submit it to be graded against hidden test cases.

Why this one is worth doing

Row major order is the default and column major order is the one that catches people out, because it needs the loops in the opposite nesting from the one that feels natural.

What to write

  1. Read rows and cols, then the grid values in row order.
  2. Print all values in ROW major order, one per line: every value of row 0, then every value of row 1, and so on.
  3. Print all values in COLUMN major order, one per line: every value of column 0 top to bottom, then column 1, and so on.
  4. Print the sum of every value.
  5. Print the largest value anywhere in the grid.

Your program reads

Two integers, rows and cols, then rows times cols integers in row order.

Your program prints

Every value row major, then every value column major, then the total and the maximum.

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
2 3
1 2 3
4 5 6
Example 1 output
1
2
3
4
5
6
1
4
2
5
3
6
21
6
Example 2 input
1 4
7 8 9 10
Example 2 output
7
8
9
10
7
8
9
10
34
10

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

Column major order puts the COLUMN loop on the outside. The subscript is still grid[r][c], only the nesting changes.

Hint 2

The enhanced for over a 2D array gives you a whole row at a time, so it takes two of them: for (int[] row : grid) then for (int value : row).

Hint 3

Seed the maximum with grid[0][0] rather than 0, or a grid of negatives reports 0.

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]