Unit 8 2D Arrays Collegeboard
- 2D array = array of arrays
- creating an array int[][] numbers;
- can initialize with values
- can initalize with for loop
- can change or access using index
Vocab
- For a 2D array, this initial traversal is used to access each array in the 2D array, and a nested for loop is needed to access each element within the selected array
- For column-major order, the inner for loop iterates through all row values, while the outer for loop iterates through each column
- Enhanced for loops with 2D arrays still require the use of nested loops. In the outer for loop, the enhanced for loop is accessing each list in the 2D array
Create a class for 2D array learning. Create a method too initialize a 2D array with arbitrary values Create a method to reverse the 2D array and print out the values Create a method that asks for the input of a position and it returns the corresponding value Create a method that multiplies each value in a row and then adds all the products together Create a new object to test out each method in the main function
public class Array{
}
import java.util.Scanner;
public class Array{
int numbers[][] = {{1,2,3},{4,5,6}};
public void forwardArray(){
for(int i = 0; i < numbers.length; i++){
for(int j = 0; j < numbers[i].length; j++){
System.out.print(numbers[i][j] + " ");
}
System.out.println();
}
}
public void reverseArray(){
for(int i = numbers.length-1;i>=0;i--){//arr[i].length=no of col in a ith row
for(int j = numbers[i].length-1; j >= 0;j--){
System.out.print(numbers[i][j] + " ");
}
System.out.println();
}
}
public void inputPosition(){
Scanner scanner = new Scanner(System.in);
System.out.println("Input row");
int row = scanner.nextInt();
System.out.println(row);
System.out.println("Input column");
int column = scanner.nextInt();
System.out.println(column);
System.out.println("Number is:" + numbers[row][column]);
}
public void multiplySum(){
int product = 1;
int sum= 0;
for(int i = 0; i < numbers.length; i++){
for(int j = 0; j < numbers[i].length; j++){
product *= numbers[i][j];
}
System.out.println("Product:" + product);
sum += product;
product = 1;
}
System.out.println("product of sums:" + sum);
}
public static void main(String[] args){
Array arrays = new Array();
arrays.forwardArray();
arrays.reverseArray();
arrays.inputPosition();
arrays.multiplySum();
}
}
Array.main(null);