FRQs intro | 2d Array Nav & sort | 2d array conclusion |
2D Arrays - accessing and updating elements
Accessing and Updating Elements in a 2D Array
Important Tips to Remember:
• Array indices start at 0: The first row and first column are at index 0.
• Relative positions: Always subtract 1 to determine the correct index relative to the 1-based numbering.
Accessing Elements
To access an element in a 2D array, use the following format:
arr[row][column]
Updating Elements
To update an element in a 2D array, assign a new value using this format:
variable_name[row][column] = new_value
For example: If you want to change the value in the second row and third column, use:
array{1]{2] = new_value
Popcorn Hack:
Write code to access the scores: 92, 70, 93 and change the last score to 100
# Example 2D array representing the scores
scores = [
[100, 85, 95, 96], # Student0
[98, 100, 100, 95], # Student1
[92, 100, 98, 100], # Student2
[100, 100, 97, 99], # Student3
[100, 100, 100, 70],# Student4
[100, 100, 99, 98], # Student5
[100, 94, 100, 93] # Student6
]
int[][] scores = {
{100, 85, 95, 96}, // Student0
{98, 100, 100, 95}, // Student1
{92, 100, 98, 100}, // Student2
{100, 100, 97, 99}, // Student3
{100, 100, 100, 70},// Student4
{100, 100, 99, 98}, // Student5
{100, 94, 100, 93} // Student6
};
System.out.println(scores[2][0]);
System.out.println(scores[4][3]);
System.out.println(scores[6][3]);
scores[6][3] = 100;
System.out.println(scores[6][3]);
92
70
93
100
Essential points:
- When accessing elements at arr[first][second], the first index is used for rows, and the second index is used for columns
- Square brackets [row][col] are used to access and modify an element of a 2d array.
HW:
public static boolean isLatin(int[][] square)
{
if(containsDuplicate(square[0]))
{
return false;
}
for(int y=0;y<square.length;y++)
{
if(!hasAllValues(square[0],square[y]) || containsDuplicate(square[y])
|| !hasAllValues(getColumn(square,y),square[y]) || containsDuplicate(hasAllValues(getColumn(square,y),square[y])))
{
return false;
}
}
return true;
}
//frq homework on google form
int[][] grid =
{
{1,-2,-3},
{-4,5,-6},
{7,-8,9}
};
public static int[][] replaceNegatives(int[][] grid)
{
for(int y=0;y<grid.length;y++)
{
for(int x=0;x<grid[y].length;x++)
{
if(grid[y][x] < 0)
{
grid[y][x] = 0;
}
}
}
return grid;
}
1
0
0
0
5
0
7
0
9