YouTube

Got a YouTube account?

New: enable viewer-created translations and captions on your YouTube channel!

English subtitles

← 2-D Arrays Part 3 - Intro to Java Programming

Get Embed Code
5 Languages

Showing Revision 5 created 05/24/2016 by Udacity Robot.

  1. To visit all elements in a Two-D array, you want to loop over the rows and
  2. columns. Let's first loop over the rows. So we have a row index i that assumes
  3. to values zero, one, and two in this example. Similarly, we'll have a column
  4. index j, then in this example, we'll go from zero to one. If we had more
  5. columns, of course it would go further. When you have a row of column index,
  6. then we can access the element at the i-th row, and the j-th column. So what
  7. you see over here. As the general expression for an element at an arbitrary row
  8. and arbitrary column. In this case, we just print it and we use printf. So that
  9. the print out lines up nicely. So we would now print this element and print
  10. that element, that would finish the innerloop. Then the outer loop would pick
  11. the next row, we print these two, and then the outer loop picks the last row.
  12. And we print those two. Now, of course, we want the numbers to line up nicely,
  13. so after printing each row, we want to print a new line. Notice that this
  14. statement is contained in the outer loop, because it happens once per row. But
  15. its not in the inner loop because we don't want a new line after every of the
  16. element. Now, lets look at the missing balance here. Of course, in this simple
  17. example I could just say I should be less than three, J should be less than
  18. two, but in general, someone might just hand you a two-dimensional array and
  19. you should ask it how big it is. Just like with a one-dimensional array, you
  20. just use the length field to find out how big an array is. You can get the
  21. number of rows from a two-dimensional array by asking it arrayname.length. And
  22. the reason for this is that a two-dimensional array is actually an array of
  23. one-dimensional arrays. So prices, which looks like this nice tabular
  24. arrangement, really is an array of three arrays, one for each row. And so the
  25. number of rows is given by that length. Now, we need to look at how many
  26. columns we have. Here you have a row. And the length of that row is the number
  27. of columns. So in general, you should remember that, for any two-dimensional
  28. array, you get the number of rows with this expression, the number of columns
  29. with that expression. Now, let's move on to doing something more interesting
  30. with two-dimensional arrays and gas prices.