What kinds of things in real life can be represented by a 2-D array?
Excel sheets, parking lots, chess boards, etc. Lots of answers!
What is wrong with this code?
for (int row = 0; row < x.length; row++) {
for (int col = 0; col < x[row].length; col++) {
System.out.print(x[col][row]);
}
}
The code will try to access the wrong elements. This could be a problem when the 2-D array is not a square, eventually giving you a IndexOutOfBounds exception (runtime error)
What is a nested loop?
A loop with in a loop.
How do you access the element in the 2nd row and 3rd column in a 2-D array x?
int[] nums = {12, 12, 45, 78, 23, 68, 0};
for (int x = 0; x <= nums.length; x++) {
System.out.println(nums[x]);
}
Runtime or logic error
The loop will try to access an element past the end of the array.
What is a ragged 2-D array?
A 2-D array where not all the rows have the same amount of columns.
NOTE: You will NOT see ragged arrays in the AP exam
What do these represent in the 2-D array x?
x.length
x[0].length
x.length -- number of rows in x
x[0].length -- number of columns in row 0
What is the mistake and what type of error is it? (runtime/logic/compiletime)
for (int i = 0; i < 4; i++){
for (int j = 0; j < i; j++) {
System.out.println(i*j);
}
j = i++;
}
Compile time error, j does not exist outside the loop
When would you use a modified for loop (for-each/enhanced for loop) over a regular for loop?
When you just want to access the elements in the array as opposed to modifying the elements. When you just care about the values at each index, not the indexes themselves.
Print out all the elements in a 2-D array x
for (int row = 0; row < x.length; row++) {
for (int col = 0; col < x[row].length; col++) {
System.out.print(x[row][col] + " ");
}
System.out.println();
}
What is the difference between runtime, compile, and logic errors?
runtime - while the code is running, an error is thrown (ex. running off the end of an array)
compile - the code can't compile (does not even run)
logic - the code does not do what it should
How many times does this code print?
for (int i = 0; i < 4; i ++) {
for (int j = i; j < 5; j++ ) {
System.out.println(i+j);
}
}
15
Given a 2-D array x, pre-filled with values, multiply each value in x with the row index and set that as the new value of that element.
for (int col = 0; col < x[row].length; col++) {
x[row][col] = row * x[row][col];
}
}
What is the issue in this code?
int count = 1;
while(count < 5) {
for (int i = 0; i < count; count++) {
if (i == 4) {
System.out.print("Hello");
}
i++;
}
}
Infinite loop in the for loop. Both i and count move up by one each time, so the loop will never stop.
What is the best loop to choose in these situations?
Changing values in a array
Running the code until you find a certain value in array
Finding the maximum in an array
1. For loop
2. While
3. Modified/Enhanced For Loop (for-each loop)