We have discussed how to define “regular arrays”, and we noticed that they are very useful for storing information. However, we can expand the dimension of the regular arrays to further dimensions to consider relationships between more than one dimension; these are called multi-dimensional arrays. In particular, we will discuss in detail two-dimensional arrays.
We will follow the same idea of single-dimensional arrays.
<data_type>[][] <id> = new <data_type>[rows][columns];
Notice that we introduce another set of square brackets [] specifying that we are going to use a two-dimensional array.
The notion of dimension may seem confusing, but in reality, the 2D array is only a relationship between two variables. Often this is called a matrix, and probably you remember that from your math class, where you solved a linear system with matrices by using addition, subtraction, and multiplication.
An array of arrays
We are interested in visualizing the 2D array in code, so what exactly is a two-dimensional array in code? If we pay attention to the definition of an array, before the [], we specify the data type. An array containing arrays of ints can be visualized as int[][]; in other words, a two-dimensional array is an array of arrays.
How do you print the array?
System.out.println(a);
[[I@9df9bb7
[[I@9df9bb7
[[I@9df9bb7
[[I@9df9bb7
System.out.println(a[i]);
[I@4241ff45
[I@1baf605d
[I@786b5131
[I@610938fb
If we plan to print the array that we declared just by itself, we will find a representation as follows:
[[I@10bbeae3
We knew that for many chapters; however, notice that printing a two-dimensional array is similar to a typewriter. A typewriter is used to type consecutive characters on a piece of paper in a horizontal form. Every time there is a keystroke, a mechanism makes the cylindrical roller advance one position at a time. When the typewriter is close to arriving at the end of the paper’s column, it moves to the next row (sometimes using a lever).
Similarly, when printing a two-dimensional array, for every row that we process, we need to process all the columns. a.length extracts the number of rows. The a[i] access the array a at position i, by using the a[i].length, will extract the size of the internal length of the array, also known as the columns.
That is why we need nesting loops to access information from the arrays in memory.
for(int i = 0; i < a.length; i++){
for(int j = 0; j < a[i].length; j++){
System.out.print(a[i][j]+"\t");
}
System.out.println();
}
Methods that take 2D array as parameters examples:
public static void print(int[][] a){
for(int i = 0; i < a.length; i++){
for(int j = 0; j < a[i].length; j++){
System.out.print(a[i][j]+"\t");
}
System.out.println();
}
}
public static int[][] populateArray(int r, int c){
int[][] a = new int[r][c];
for(int i = 0; i < r; i++){
for(int j = 0; j < c; j++){
a[i][j] = (int)(Math.random()*16);
}
}
return a;
}
AP CS A
[Using Methods]
MOD-2.C.3 A precondition is a condition that must be true just prior to the execution of a section of program code in order for the method to behave as expected. There is no expectation that the method will check to ensure preconditions are satisfied.
MOD-2.C.4 A postcondition is a condition that must always be true after the execution of a section of program code. Postconditions describe the outcome of the execution in terms of what is being returned or the state of an object.
MOD-2.C.5 Programmers write method code to satisfy the postconditions when preconditions are met.
[Documentation Comments]
MOD-2.C.3 A precondition is a condition that must be true just prior to the execution of a section of program code in order for the method to behave as expected. There is no expectation that the method will check to ensure preconditions are satisfied.
MOD-2.C.4 A postcondition is a condition that must always be true after the execution of a section of program code. Postconditions describe the outcome of the execution in terms of what is being returned or the state of an object.
MOD-2.C.5 Programmers write method code to satisfy the postconditions when preconditions are met.
[while Loop]
CON-2.H Compute statement execution counts and informal run-time comparison of iterative statements.
CON-2.H.1 A statement execution count indicates the number of times a statement is executed by the program.
[do-while Loop]
CON-2.C.1 Iteration statements change the flow of control by repeating a set of statements zero or more times until a condition is met.
[Random Numbers]
CON-1.D.4 The values returned from Math.random can be manipulated to produce a random int or double in a defined range
[Accessing and Processing Array Elements]
CON-2.I For algorithms in the context of a particular specification that requires the use of array traversals— a. Identify standard algorithms b. Modify standard algorithms c. Develop an algorithm;
VAR-2.C.1 An enhanced for loop header includes a variable, referred to as the enhanced for loop variable.
VAR-2.C.2 For each iteration of the enhanced for loop, the enhanced for loop variable is assigned a copy of an element without using its index.
VAR-2.C.3 Assigning a new value to the enhanced for loop variable does not change the value stored in the array.
VAR-2.C.4 Program code written using an enhanced for loop to traverse and access elements in an array can be rewritten using an indexed for loop or a while loop.
[Array Operations]
CON-2.I.1 There are standard algorithms that utilize array traversals to— ● Determine a minimum or maximum value ● Compute a sum, average, or mode ● Determine if at least one element has a particular property ● Determine if all elements have a particular property ● Access all consecutive pairs of elements ● Determine the presence or absence of duplicate elements ● Determine the number of elements meeting specific criteria
CON-2.I.2 There are standard array algorithms that utilize traversals to— ● Shift or rotate elements left or right ● Reverse the order of the elements
ACM CCECC
[Using Methods]
SDF-14. Analyze programming code that utilizes preconditions, postconditions, and invariants.
Explain the importance of algorithms in the problem-solving process.
Demonstrate how a problem may be solved by multiple algorithms, each with different properties.
Read a given program, and explain what it does
Trace the flow of control during the execution of a program (both correct and incorrect).
Use appropriate terminology to identity elements of a program (e.g., identifier, operator, operand)
Reading and explaining code
Basic concepts such as variables, primitive data types, expression evaluation, assignment, etc.
Apply basic programming style guidelines to aid readability of programs such as comments, indentation, proper naming of variables, etc.
Basic testing (perhaps using suitable frameworks) including test case design
Basic concepts such as variables, primitive data types, expression evaluation, assignment, etc.
Key modularity constructs such as functions (and methods and classes, if supported in the language) and related concepts like parameter passing, scope, abstraction, data encapsulation, etc.
When and how to use standard data structures
Structured data types available in the chosen programming language like sequences (e.g., arrays, lists), associative containers (e.g., dictionaries, maps), others (e.g., sets, tuples) and when and how to use them.