**Please help…the answer key says that B is correct, but I can’t figure out why. I’m a new AP CSA teacher and I can’t figure it out. TIA for your help. **
Question: Consider the following code segment.
int array2D = {{1, 2, 3, 5},
{5, 2, 7, 9},
{10, 3, 4, 1},
{8, 3, 5, 6}};
for (int row = 0; row < array2D.length; row++) {
for (int col = 0; col < array2D[0].length; col++) {
if (array2D[row][col] == num) {
System.out.print(row + array2D[row][col] + " ");
}
}
}
What is printed when num has the value 5?
A. 4 1 3
B. 5 6 8
C. 6 7 9
D. 8 5 7
E. 9 6 8
Hey there @jennifer.couling,
Let’s start with step by step instructions going down
int array initialization: nothing new just including the dataset
Iterator loop: here were going to go through two loops
// this allows access to the first dimension of the array
for(row is 0; row is less than my array2D; row++) {
// this grants us the second dimension of being able to get numbers
// rather than the arrays on the first dimension
// this iteration is called every time that row is less than array2D’s length
for(col is 0; col is less than array2D[0]; col++) {
if index of array2D[row][col] is 5 then {
display (row + array2D[row][col] + " ")
}
}
}
by using this we iterate through every index within the list starting at index 0
if we look ourselves we can see that it matches at 3 times at indices [0][3] & [1][0] & [3][2] since we now have our matches that satisfy our conditional we can now move on to displaying our output which is taking the current row and adding it to the matching indexes since we have a match at 0, 1 and 3 all we have to do is add 5 to those results giving our pair of 5, 6, and 8 making the correct answer B
Hope this answers your question!
2 Likes
That helps so much! That’s similar to what I was thinking as I kept running the code and changing numbers
1 Like