Rows, Columns, and Higher Dimensions, Explained

UPI Study › Courses › Data Structures and Algorithms › Free lessons › Lesson 5.3 Free with a free account

Rows, Columns, and Higher Dimensions

Data Structures and Algorithms · Chapter 5: ArraysSection 5.3 · lesson 18 of 8710 min · free with a free account

← Rearranging Elements Within a Fixed-Size CollectionNext lesson: Determining Whether Two Collections Hold Identical Content →

Earn 3 college credits for Data Structures and AlgorithmsRecommended for credit by NCCRS · Computer Science 251 · self-paced · one payment, lifetime access

In this lesson

Build, traverse and transform two- and three-dimensional arrays in Java.

  • Create and index two-dimensional arrays as arrays of row arrays
  • Traverse rectangular and jagged arrays with correct nested loop bounds
  • Compute row, column and grand totals and transpose a grid
  • Extend the same ideas to three-dimensional arrays and real applications

Free study notes

Get this lesson's notes by email

The key points and 4 practice questions with answers, in your inbox. One email, free.

One email. Unsubscribe in one click.

Transcript

Everything said in the video, section by section (1,430 words). Read along, or search it.

Opening Question

Sales by Region and Quarter

A company tracks its sales for three regions, over four quarters. That's twelve numbers. Kept in one long array, every question starts with arithmetic. Which slot holds region one, quarter two? A table answers directly. Name the row, name the column, and the number sits where they meet. Java builds that table out of arrays of arrays.

Creating Grids

Two Pairs of Brackets

A two-dimensional array is written with two pairs of brackets. This initializer lists the table row by row, one brace list per row. Index it with two numbers, row first, then column. So sales, one, two, means row one, column two. Run it. Sales dot length is three, the number of rows. Row zero's length is four, the number of columns. And row one, column two holds one hundred ten. The other way to create one gives the sizes. New int, three, four, makes three rows of four, and every slot starts at zero.

Runtime Error

Row Index Out of Range

Both indexes must be in range. Rows run from zero to length minus one, and so do the columns in each row. Ask for row three of this three-row grid, and the program compiles, then stops while it runs. The message names the bad index, three, and the length it broke: the outer array's length, which is also three.

Key Idea

An Array of Row Arrays

That table picture is convenient, but it isn't quite what Java builds. A two-dimensional array is an array whose slots hold arrays. The outer array has one slot per row, and each slot refers to a separate row array. So a row is an ordinary value. Sales, one, on its own is an int array, which you can store, pass to a method, or replace. Walking along a row stays inside one row array. Walking down a column jumps from row array to row array. So row by row is the natural order, called row-major order.

Row-Major Order

Numbering Cells in One Line

Row-major order also numbers every cell in one long line. In a grid with cols columns, row r, column c is number r times cols, plus c. This loop stores each cell's own number in it, and deep to string prints the nested rows. The numbers run along each row, and carry on in the next. Row one, column two is one times four, plus two: six. Many file formats store tables and images this way. Plain to string would print only what the outer slots hold: references to row arrays, which look like this.

Copying Pitfall

Clone Copies Only the Outer Array

Arrays of arrays also change what copying means. Here, same is just a second name for a, and shallow is a's clone. Set a, zero, zero to ninety-nine, and both print ninety-nine. Clone copied only the outer array, and its slots still refer to a's rows. But replacing a whole row of shallow changes only shallow's own slot, so a, one, zero is still three. A true copy needs new row arrays too.

Jagged Arrays

Rows of Different Lengths

Because every row is its own array, rows don't need the same length. An array like that is called jagged. Create the outer array with the row count only. Each slot then holds null, as the first print shows, until a row is assigned. Pascal's triangle fits naturally. Row r gets r plus one slots, both ends are one, and each inner entry adds the two entries above it. The printing loops never assume a width. The for-each loop hands over one row at a time, and the inner loop walks whatever length that row has.

Nested Loops

Visiting Every Cell

Visiting every cell takes one loop per dimension. The outer loop picks a row, and the inner loop walks along it. Look at the two bounds. The outer loop stops at sales dot length, the number of rows. The inner loop stops at the length of the current row. That costs nothing on a rectangle, and keeps the same code correct for jagged arrays. Percent five d prints each number five characters wide, so the columns line up.

Traversal Order

Row by Row or Column by Column

Swap the two loops, and the order changes. With rows outside, cells are visited row by row. With columns outside, they're visited column by column, down each column in turn. Column order suits answers that belong to a column. On a jagged array, though, a column loop must check that each row is long enough.

Worked Example

Row, Column and Grand Totals

Totals work inside nested loops too. The skill is deciding where each result belongs. A row sum belongs to a row, so it gets one slot per row. A column sum gets one slot per column. The grand total is a single variable. One pass fills all three. Row zero adds up to five seventy-five, and quarter zero, down column zero, comes to two seventy. Both sets of sums add up to the same total, twelve ninety. That agreement is a handy check on your own work. A search works the same way, except that the loop remembers a position, a best row and a best column, instead of a total.

Quick Check

The Wrong Inner Loop Bound

Quick check. This program adds up a grid with two rows and four columns, using the same nested loops. What does it print? Thirty-six, fourteen, or does it stop at an index out of bounds? Pause and predict. It prints fourteen. The inner loop stops at g dot length, the number of rows, which is two. So it adds only columns zero and one. One plus two, plus five plus six, is fourteen. Columns two and three are skipped silently, with no error at all. Thirty-six needed the bound g, r, dot length. And an exception needs more rows than columns, so the wrong bound runs past the end of a row.

Transposition

Swapping Rows and Columns

Transposing a grid swaps its rows and columns: the item at row r, column c, moves to row c, column r. A grid of two rows and three columns becomes three rows of two. So the result is a new array, with its sizes reversed. Run it. Row zero of the original, one, two, three, now stands up as column zero of the new grid.

In-Place Transpose

Swapping Each Pair Exactly Once

A square grid can be transposed in place, by swapping each item with its mirror image across the diagonal. The inner loop starts at r plus one, so each pair is swapped exactly once. Run it, and the rows have become columns. Now start the inner loop at zero, a common slip. Every pair is swapped twice, and the second swap undoes the first. The grid comes out exactly as it went in, with no error message. That's why it's worth knowing in advance.

Three Dimensions

Layers, Rows and Columns

If an array can hold arrays, those arrays can hold arrays too. A three-dimensional array is a stack of tables. The first index chooses the layer, and the other two choose the row and column inside it. Here, two layers of three by four. Filling it with a counter, in loop order, puts twenty-three in the very last cell: layer one, row two, column three. And two indexes alone pick out a whole row. Layer one, row zero, is twelve through fifteen. Each extra dimension adds a pair of brackets, an index, and a nested loop. The item count is the product of the sizes: four by five by six is already one hundred twenty.

Applications

Game Boards, Tables and Images

Grids show up everywhere. A game board is a grid of characters, checked row by row, column by column, and along the diagonals. A data table has categories on both axes, like the sales table, with its row and column sums. A grayscale image is a grid of brightness values, from zero for black up to two fifty-five for white. Editing a picture means traversing its grid. And a color image adds a third dimension: red, green and blue values for every pixel.

Quick Check

A Missing Row in a Jagged Array

One more check. This program builds a jagged array of seat rows, with room for three rows. It fills in two of them, then adds up every row's length. What happens? Pause and predict. It stops at row one. Only rows zero and two were ever created, so slot one still holds null. The for-each loop hands that null over as a row, and asking for its length throws a null pointer exception. The message can't name the variable, because javac didn't keep local names, but the line number points straight at it. Ten would need every row created first.

Key Takeaways

Grids in Summary

To sum up. A two-dimensional array is an array of row arrays, indexed row first, then column. Rows can differ in length, so loop bounds use the length of each row. Totals need a slot wherever the result belongs, and an in-place transpose swaps each pair once. Each extra dimension adds one index, and one nested loop.

About Data Structures and Algorithms at UPI Study

Data Structures and Algorithms (Computer Science 251) is a self-paced online course of 87 video lessons in 17 chapters, from Java and object-oriented design to arrays, linked lists, recursion, stacks and queues, trees, heaps, hash tables, sorting and graphs. It carries a NCCRS credit recommendation for 3 semester credits.

Every lesson transcript is free on pages like this one, and the videos are free with a free UPI Study account. Enrolling adds a practice quiz after each lesson, the graded work and final exam that earn the credit, lifetime access, and an official transcript on completion. UPI Study has helped over 130,000 students with college credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Compare: Discrete Math vs Data Structures and Algorithms · Intro to Java vs Data Structures and Algorithms

Why take it here

Why students take Data Structures and Algorithms with UPI Study

How programs store and search dataData Structures and Algorithms teaches how to organize data and measure how fast code runs: arrays, linked lists, stacks, queues, trees, heaps, hash tables, sorting and graphs, all written in Java. It is a core course in computer science and software degrees.
Credit at a fraction of the priceThe same 3 credits can cost $750 or more at a US college. Here it is one payment, self-paced, with lifetime access.
Finish your degree soonerTransfer credits reduce the courses you still owe, so you can graduate earlier or lighten a heavy semester.
Strengthen an applicationA completed college-level course on an official transcript shows admissions and scholarship committees you can do the work.
Study on your own scheduleNo start dates, no deadlines. Watch the lessons, practice, and take the final when you are ready.
130,000+students helped with college creditsACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Where the credit goes

Universities that work with NCCRS

Data Structures and Algorithms carries a NCCRS credit recommendation. These universities work with NCCRS; some are UPI Study's signed partners. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.

Find my college → Not listed? Ask Athena in the corner of this page, or book a 15-minute call.

FAQ

Questions students ask us

About Rows, Columns, and Higher Dimensions

How do you declare a 2D array in Java?
Use two pairs of brackets, as in int[][] sales = new int[3][4];, which makes three rows of four columns with every slot starting at 0. You can also list the values row by row, as in int[][] g = {{1, 2}, {3, 4}};. Index with the row first and then the column, so sales[1][2] means row 1, column 2.
What is a jagged array in Java?
A jagged array is a two-dimensional array whose rows have different lengths. It works because each row is a separate array: create the outer array with only a row count, as in int[][] tri = new int[5][];, then assign each row its own array. Until a row is assigned, its slot holds null, so loops should use each row's own length, such as tri[r].length.
How do you loop through a 2D array in Java?
Use one loop per dimension: the outer loop picks a row and the inner loop walks along it. Bound the outer loop by grid.length, the number of rows, and the inner loop by grid[r].length, the current row's length. Using grid.length as the inner bound is a common slip that silently skips columns when a grid has more columns than rows.
How do you transpose a matrix in Java?
Transposing moves the item at row r, column c to row c, column r, so a grid with 2 rows and 3 columns becomes a new grid with 3 rows and 2 columns. A square grid can be transposed in place by swapping each item with its mirror across the diagonal, starting the inner loop at r + 1. Starting it at 0 swaps every pair twice, leaving the grid unchanged.

About the Data Structures and Algorithms course

How many college credits is Data Structures and Algorithms?
Data Structures and Algorithms (Computer Science 251) carries a NCCRS credit recommendation for 3 semester credits. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities.
How much does Data Structures and Algorithms cost and what is included?
$250, paid once, with lifetime access: all 87 video lessons, a practice quiz after each, the graded work and final exam, and an official transcript when you finish. Students who want several courses choose UPI Study PRO instead.
Which universities accept UPI Study credits?
UPI Study has signed partner agreements with universities such as Thomas Edison State University, University of the People and Charter Oak State College, and works with universities such as Penn State, SNHU and SUNY. ACE and NCCRS have over 2,100 cooperating colleges that will consider accepting credits; the final decision is with the universities. Use "Find my college" on this page to check yours.
How long does Data Structures and Algorithms take?
It is self-paced with no deadlines. The 87 lessons total about 15 hours of video; most students add reading and practice time and finish in a few weeks to a few months, on their own schedule.
How are the exams done?
Quizzes and assignments are online in the course. The final exam is taken online with proctoring; a person on the UPI Study team checks assignments, usually within two days.
How do my credits reach my college?
When the course shows 100% complete, request the official transcript from your dashboard. It is sent to the college you name, and you can send it to more than one. Check your college first with "Find my college" on this page, or ask Athena.

Ready for the full course? Earn 3 credits in Data Structures and Algorithms.

87 video lessons, a quiz after each one, and the graded work that earns the credit. Recommended for credit by NCCRS.

Data Structures and Algorithms
3 credits · NCCRS
Enroll →