Chapter 8 Multidimensional Arrays Flashcards
What is the syntax for declaring an array reference variable:
dataType[][] refVar;
[][] is the # of dimensions you want
Create an arrayand assign its reference to variable
refVar = new dataType[10][10];
Combine declaration and creation in one statement (row = 10, col = 10):
dataType[][] refVar = new dataType[10][10];
Declaring variables of two dimensional arrays[10][10] and creating two dimensional arrays syntax
int[][] matrix = new int[10][10];
or
int matrix [] [] = new int[10][10];
Access an element of a 2D array:
matrix[0][0] = 3;
Assign each element of the array a random number:
for (int i = 0; i < matrix.length; i++){
for (int j = 0; j < matrix[i].length; j++){
matrix[i][j]; = (int)(Math.random() * 1000);
Declare, initialize, and create a two dimensional array with 3 rows and 3 columns with values ascending from 1-12.
int[][] array = {
{1,2,3}
{4,5,6}
{7,8,9}
{10,11,12}
}
;
How would you express a two dimensional array with 3 rows and 4 columns
int[][] x = new int[column][row];
ex.
int[][] x = new int[3][4]
Array start at array[0].length. Calling beyond the index causes:
ArrayIndexOutOfBoundsException
Ragged arrays definition
Each row in a two dimensional array is itself an array, so each row can have different lengths.
Not a solid block, like an increasing or decreasing triangle
Declare and initialize a random array syntax with 5– rows and 4 cols with values {1,2,3,4,5}, {2,3,4,5}, {3,4,5}, {4,5}, [5}.
int[][] matrix = {
{1,2,3,4,5}
{2,3,4,5}
{3,4,5}
{4,5}
{5}
}
};
7 ways of processing arrays
- Initializing arrays with input values
- Printing arrays
- Summing all elements
- Summing all elements by column
- Which has the largest sum
- Finding the smallest index of the largest column
- Random Shuffling
Initializing arrays with input values:
import java.util.Scanner;
Scanner input = new Scanner(System.in);
System.out.println(“Enter “ + matrix.length + “ rows and “ + matrix[0].length + “columns: “);
for (int row = 0; row < matrix.length; row++){
for (int col = 0; col < matrix[row].length; col++){
matrix[row][col] = input.nextInt();
}
}
Printing arrays
for (int row = 0; row < matrix.length; row++){
for(int col= 0; col < matrix[row].length; col++){
System.out.print(matrix[row][col] + “ “);
}
System.out.println();
}
Summing all elements
int total = 0;
for (int row =0; row < matrix.length; row++){
for(int col= 0; col < matrix[row].length; col++){
total += matrix[row][col];
}
}