2d Arrays Lesson
2d Arrays
- Declaring 2d arrays different ways
- Initializing 2d arrays
- Printing 2d arrays with for loops vertically vs horizontall
- Printing 2d arrays backwards
int[][] intArray;
double[][] doubleArray;
String[][] stringArray;
boolean[][] booleanArray;
//Method 1
int[][] intArray = new int[3][2]; //will have to manually write out values though if random:
intArray[0][0] = 20; //... till [2][1]
System.out.println(intArray[0][0]);
//Method 2
int[][] intArray2 = {{1,2},{3,4},{5,6}};
System.out.println(intArray2[1][1]);
//String Method 1
String[][] stringArray = new String[2][2];
stringArray[0][0] = ("hello world"); //... till [1][1]
System.out.println(stringArray[0][0]);
//String Method 2
String[][] stringArray2 = {{"one","two"},{"three","four"}};
System.out.println(stringArray2[1][1]);
System.out.println("Vertically:");
int[][] matrix = {{1,3,7,8}, {4,5,9,1}, {1,9,6,2}};
for (int i = 0; i<3; i++) {
for (int j = 0; j<4; j++){
System.out.println(matrix[i][j]);
}
}
System.out.println("Horizontally:");
int[][] matrix = {{1,3,7,8}, {4,5,9,1}, {1,9,6,2}};
for (int i = 0; i<3; i++) {
for (int j = 0; j<4; j++){
System.out.print(matrix[i][j]+ " ");
}
}
System.out.println();
System.out.println("Horizontally decreasing:") ;
for (int count = 3; count >=1; count--){
for (int col = 0; col<matrix[0].length; col++) {
for (int row = 0; row<count; row++){
System.out.print(matrix[row][col] + " ");
}
System.out.println();
}
}
System.out.println("Forwards:");
int[][] matrix = {{1,3,7,8}, {4,5,9,1}, {1,9,6,2}};
for (int i = 0; i<3; i++) {
for (int j = 0; j<4; j++){
System.out.print(matrix[i][j]+ " ");
}
}
System.out.println();
System.out.println("Backwards:");
int[][] matrix = {{1,3,7,8}, {4,5,9,1}, {1,9,6,2}};
for (int row = matrix.length-1; row>=0; row--) {
for (int col = matrix[0].length-1; col>=0; col--){
System.out.print(matrix[row][col]+ " ");
}
}