HW 2 - Traversing 2D Arrays
HW 2 - Traversing 2D Arrays
What should replace /* missing code */ so that a 2 is stored in every cell in the array?
What are the contents of mat after the code segment has been executed?
(A)
{{0, 1, 2},
{10, 11, 12},
{20, 21, 22},
{30, 31, 32},
{40, 41, 42}}
(B)
{{0, 10, 20, 30, 40},
{1, 11, 21, 31, 41},
{2, 12, 22, 32, 42}}
(C)
{{0, 1, 2, 3, 4},
{10, 11, 12, 13, 14},
{20, 21, 22, 23, 24}}
(D)
{{0, 10, 20},
{1, 11, 21},
{2, 12, 22},
{3, 13, 23},
{4, 14, 24}}
(E)
{{11, 21, 31, 41, 51},
{12, 22, 32, 42, 52},
{13, 23, 33, 43, 53}}
The following code segment appears in the main method of the same class. What is printed when this code is
executed?
(A) 3
(B) 1
(C) 4
(D) 0
(E) 2
_____ 4) Suppose we wish to traverse a 2-d array of strings named grid with two for-each loops. Which of the
following represents the loop headers we should use?
(A)
for (String row : grid)
{
for(String str : row)
{
(B)
for (String[][] row : grid)
{
for (String[] str : row)
{
(C)
for (String[] row : grid)
{
for(String[] str : row)
{
(D)
for (String[] row : grid)
{
for (String str : grid[row])
{
(E)
for (String[] row : grid)
{
for (String str : row)
{
The following code segment appears in another method in the same class.
Which of the following represents the contents of arr as a result of executing the code segment?
(A) {6, 4, 2, 4}
(B) {1, 6, 3, 4}
(C) {4, 3, 6, 1}
(D) {4, 4, 2, 2}
(E) {2, 2, 4, 4}
6) Write a public static method diagSum, which takes a 2d array of int values as a parameter, and returns the
sum of the elements in the lead diagonal as an int value. The lead diagonal is defined as the diagonal line of
values starting in the top left corner and proceeding one step right and down for each value until either the
bottom or right edge of the array is reached. For example, in the array represented below, the numbers
underlined represent the lead diagonal.
2 4 5 8
1 1 6 5
3 4 5 2
diagSum(example) would return 8. Assume the array passed has at least 2 rows and 2 columns.