Reputation: 21
I need an explanation of why this code prints "1", I'm taking my final exam tomorrow and this is a practice question that I cannot answer.... Any input is greatly appreciated!
public class Test {
public static void main(String[] args) {
int[][] values = {{3, 4, 5, 1}, {33, 6, 1, 2}};
int v = values[0][0];
for (int[] list : values)
for (int element : list)
if (v > element)
v = element;
System.out.print(v);
}
}
Upvotes: 0
Views: 218
Reputation: 60414
What do you think this code is supposed to do? Currently, it's printing the lowest number found. Why? Because for each element it performs the following check:
if (v > element)
v = element;
...where
v = <the smallest number found so far>
values[0][0]
-- because, well, it is the smallest number found at that point, since we haven't yet looked at any elements.v
contains the smallest number seen so far.I strongly recommend stepping through the code in a debugger or (even better) writing down the steps on paper, testing the loop invariants at each iteration.
Upvotes: 1
Reputation: 1066
Well we need to check step by step
First
you got you main 2 dimensions array
int[][] values = {{3, 4, 5, 1}, {33, 6, 1, 2}};
Then you assign to a var V int. With the data of [0][0].
Note that values[0] = 3,4,5,1
values[0][0] = 3
int v = values[0][0];
Then the 2 for cheek each value in the array. First in values[0-1] and then values[][0-3]
for (int[] list : values)
for (int element : list)
Finally you check if the V is greater than the new values you get. IF it is it substitute
if (v > element)
v = element;
this code get's you the smallest number in the array. The first number. If you have two 1 it will take the first one.
I hope it help
Upvotes: 1
Reputation: 63797
Because the code below will give you the smallest value in your nested array values
, which is indeed 1 in your code.
if (v > element)
v = element;
If v
is larger than current element
(ie. element
is smaller than v
), assign element
to v
.
Upvotes: 6
Reputation: 20235
You are iterating through all the elements in the array and setting v
to the element if it is greater than the element if (v > element) v = element;
. Therefore, you will end up with the smallest value, which is 1.
Upvotes: 1