Two –Dimensional Arrays Mrs. C. Furman September 18, 2008
The “for each” loop A shortcut with for loops. Used to iterate through a sequence of elements in an array or ArrayList. The body of the loop is executed for each element in the array or ArrayList. At the beginning of each iteration, the next element is assigned to the control variable. Works the same as a standard for loop that loops through all elements of the data structure. The control variable in “for each” is assigned to the value at each index, where the standard for loop is being assigned the index.
The “for each” loop structure for (Type variable : collection) statementsExample: int [] myList = {1, 3, 5, 7, 9}; int sum = 0; for (int i : myList) sum += i; sum += i;
Example 1 Write a “for each” loop that prints all elements in the array data.
Example 2 Re-write the following loop using for each: list is an ArrayList of Double. List mylist = new ArrayList (); for (int i = 0; i < mylist.size(); i++) for (int i = 0; i < mylist.size(); i++) { System.out.println (mylist.get(i)); System.out.println (mylist.get(i)); }
Two Dimensional Arrays rows and columns, also called a Matrix we must specify the number of row and columns we will need when we construct the 2DArray. Similar to Arrays. Example: int [][] magicSquare = new int [4][4];
Accessing Elements in a 2D Array Elements are indexed [row][column] magicSquare [0][0] = 3; magicSquare [1][3] = 5; int myNum = magicSquare [1][3];
Initializer List for 2D int [][]cars = {{10, 7, 12, 10, 4}, {18, 11, 15, 17, 10}, {18, 11, 15, 17, 10}, {12, 10, 9, 5, 12}, {12, 10, 9, 5, 12}, {16, 6, 13, 8, 3}}; {16, 6, 13, 8, 3}}; GM Ford Toyota BMW red brown black white gray
Getting Size .length gives us the number of rows… then when we access a specific row, we do.length to get number of columns. int[][] list = {{1,2,3, 4}, {1}, {1, 2, 3}}; int numRows = list.length;//3 int firstCol = list[0].length;//4 int secCol = list[1].length;//1 int thirdCol = list[2].length;//3
Looping Through a 2D Array Example 3: Write a nested for loop to output all elements in the 2D array.
Multiplication Table Write a loop that will assign a 5 x 5 2D Array to the multiplication tables of The result will look like the below 2D Array