Download presentation
Presentation is loading. Please wait.
Published byAnnabelle Miller Modified over 9 years ago
1
Two –Dimensional Arrays Mrs. C. Furman September 18, 2008
2
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.
3
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;
4
Example 1 Write a “for each” loop that prints all elements in the array data.
5
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)); }
6
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]; 0000 0000 0000 0000 0 1 2 3 01230123
7
Accessing Elements in a 2D Array Elements are indexed [row][column] magicSquare [0][0] = 3; magicSquare [1][3] = 5; int myNum = magicSquare [1][3]; 3000 0005 0000 0000 0 1 2 3 01230123
8
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}}; 10712104 1811151710 12109512 1661383 GM Ford Toyota BMW red brown black white gray
9
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
10
Looping Through a 2D Array Example 3: Write a nested for loop to output all elements in the 2D array.
11
Multiplication Table Write a loop that will assign a 5 x 5 2D Array to the multiplication tables of 0..4. The result will look like the below 2D Array 00000 01234 02468 036912 0481216 0 1 2 3 4 0123401234
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.