Comp 110 2D Arrays: Operations and Usage

2D Arrays: operations and usage

Assigning to inner array:

<name>[rowIndex][columnIndex] = <value>; // Example
let arr: number[][] = [[1, 2, 3],                         
                      [4, 5, 6],                         
                      [7, 8, 9]];
randomArray[2][2] = 100;
// This will put replace 9 with 100 in the 2nd row, 2nd column of the array

Accessing element of inner array:

<name>[rowIndex][columnIndex];  // Example
let arr: number[][] = [ [1, 2, 3],                         
                        [4, 5, 6],                         
                        [7, 8, 9] ];
print(randomArray[2][2]);
// This will print 9, the element in the 2nd row and 2nd column of the array.

Getting # of elements of inner array:

<name>.[rowIndex].length; // Example
let a: number[][] = [[1, 2, 3, 4],                        
                     [5, 6, 7, 8]];
print(a[0].length);
// This will print 4, the length of the 0th row. The length of each row is equal to the number of columns!

Assigning to outer array:

<name>[rowIndex] = <array of correct type>; // Example
let arr: number[][] = [[1, 2, 3],                         
                       [4, 5, 6],                        
                       [7, 8, 9]];
randomArray[2] = [1, 2, 3];
// This will reassign the 2nd row of the array to be [1, 2, 3]

Accessing element of outer array:

<name>[rowIndex]; // Example:
let arr: number[][] = [[1, 2, 3],
                       [4, 5, 6],
                       [7, 8, 9] ];
let y: number[] = arr[2];
print(y);
// [7, 8, 9] will be printed

Getting number of elements of outer array:

<name>.length; // Example:
let a: number[][] = [[1, 2, 3, 4],
                    [5, 6, 7, 8]];
print(a.length)
// 2 will be output to the screen. This is the number of rows in our 2D array.

Note that all of these examples were written using row-major conventions!