2D Array Exercises

advertisement
2D Array Exercises
1. Write a declaration statement to create a 2D array variable named int2D for a 2D array of ints.
2. _____ How many array objects are created by your code for question #1 above?
3. Write an assignment statement that gives int2D a 2D array of 3 rows and 2 columns.
4. _____ How many array objects are created by your code for question #3 above?
5. ____________________ What are the six values stored in int2D ?
6. Print the number of elements in int2D (don't use hard-coded numbers in your code!).
7. Change each of the elements in int2D to a value that equals its row index times its column index.
8. Print each of the elements in int2D in row major order using indexed for loops. Print a space after
each item in a row and a new line between each row.
Robert Glen Martin
-- 1--
School for the Talented and Gifted
9. Print each of the elements in int2D in row major order using for-each loops. Print a space after
each item in a row and a new line between each row.
10. Write a single statement to declare and initialize int2D2 to contain the following elements:
3 4 5 6
0 9 8 7
11. Write statements to replace every element of int2D2 with half its previous value.
12. Draw a diagram showing the values of int2D2 and each of the associated arrays. Assume that
int2D2 has the values from question #11 above.
13. Assume that after question #11, the statement int2D = int2D2; is executed. How many new
array objects are created?
Robert Glen Martin
-- 2--
School for the Talented and Gifted
14. Complete the findMin method to return the smallest element of m. Use indexed loops.
// Precondition: m.length > 0 and m[0].length > 0
public static double findMin(double[][] m)
{
}
15. Complete the findMin method to return the smallest element of m. Use for-each loops.
// Precondition: m.length > 0 and m[0].length > 0
public static int findMin(int[][] m)
{
}
Robert Glen Martin
-- 3--
School for the Talented and Gifted
16. Assume that str2D has been declared and initialized with a 2D array of Strings. Write code to
replace each of str2D's elements with "even" or "odd". "even" should be assigned to elements
where the sum of the row and column indexes is even, and "odd" should be assigned otherwise.
17. Assume that you have a rotateArr(int[] arr) method which “rotates” the elements in arr so
that each element is moved to the next index and the item at the end is moved to the first index. For
example, {5, 6, 2, 0, 4} becomes {4, 5, 6, 2, 0}.
Complete rotateMatrix so that it “rotates” each of the rows in m. You must use rotateArr to
perform the actual rotations.
public static void rotateMatrix(int[][] m)
{
}
Robert Glen Martin
-- 4--
School for the Talented and Gifted
Download