2d Arrays Lesson
2d Arrays
int [][] numbers1 = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}};
int[][] numbers2 = new int[4][3];
for(int i = 0;i<alphabet.length;i++){
for(int j = 0; j < alphabet[i].length;j++){ //nested for loops
System.out.print(alphabet[i][j]+" ");
}
System.out.println(" ");
}
int[][] numbers = new int[2][2]; //method 2: Creates array with two rows and two columns
numbers[0][0] = 1;
numbers[0][1] = 4;
numbers[1][0] = 9;
numbers[1][1] = 16;
import java.util.Scanner;
public class Arrays{
int[][] numbers = {{5,1,3,4},{3,8,7,6},{9,12,14,13}};
public void printNum() {
System.out.println("\nForwards");
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 reverse() {
System.out.println("\nReverse");
for (int i = numbers.length - 1; i >= 0; i--){
for(int j = numbers[i].length - 1; j >= 0; j--) {
System.out.print(numbers[i][j]+ " ");
}
System.out.println();
}
}
public void userInput(){
System.out.println("\nInput");
Scanner scanner = new Scanner(System.in);
System.out.print("Row: ");
int rowIndex = scanner.nextInt();
System.out.println(rowIndex);
System.out.print("Column: ");
int columnIndex = scanner.nextInt();
System.out.println(columnIndex);
System.out.println("Result = " + numbers[rowIndex][columnIndex]);
}
public void sumOfProducts(){
System.out.println("\nSum of Row Products");
int a = 1;
int b = 0;
for (int j = 0; j < numbers.length; j++) {
for(int i = 0; i < numbers.length; i++){
a = a*numbers[j][i];
}
b = b + a;
System.out.println("product of row " + j + " = " + a);
a = 1;
}
System.out.print("sum of rows = " + b);
}
public static void main(String[] args){
Arrays array = new Arrays();
array.printNum();
array.reverse();
array.userInput();
array.sumOfProducts();
}
}
Arrays.main(null);