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
Free preview
Create a free account to keep watching
It takes a minute and costs nothing. Your free account unlocks all of Chapter 1 and 3 more lessons of Data Structures and Algorithms.
Lesson complete
Earn the 3 college credits for Data Structures and Algorithms
Enrolling adds a quiz after each lesson, the graded work and the official transcript. Recommended for credit by NCCRS.
Next lesson: Determining Whether Two Collections Hold Identical Content →← Rearranging Elements Within a Fixed-Size CollectionNext lesson: Determining Whether Two Collections Hold Identical Content →
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.
Enroll now → Course details Download the syllabus All Computer Science courses Every course with PRO →
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
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.
Thomas Edison State UniversitySigned partner
University of the PeopleSigned partner
Charter Oak State CollegeSigned partner
Strayer UniversitySigned partner
Columbia Southern UniversitySigned partner
Indiana TechSigned partner
Penn StateWorks with NCCRS
Southern New Hampshire UniversityWorks with NCCRS
SUNYWorks with NCCRS
+many more cooperating universitiesFind my college →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?
What is a jagged array in Java?
How do you loop through a 2D array in Java?
How do you transpose a matrix in Java?
About the Data Structures and Algorithms course
How many college credits is Data Structures and Algorithms?
How much does Data Structures and Algorithms cost and what is included?
Which universities accept UPI Study credits?
How long does Data Structures and Algorithms take?
How are the exams done?
How do my credits reach my college?
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.
3 credits · NCCRSEnroll →