Skip to content
Advertisement

Why do we initially set min and max to the first value in the array when trying to find the minimum and maximum value?

I’ve been learning Java for a while and I’ve run into a problem I can’t figure out. I am currently learning arrays and how to iterate through them using loops. I generally understand how the if statement and the for loop work, but in this case I don’t understand the principle of this loop in combination with if statements. This is the example I’m talking about:

JavaScript

I want to focus on this part:

JavaScript

The only thing I understand from this is how this for loop works, but the instruction min = max = nums[0]; is unclear to me. Why are we assigning these values to each other? Probably because I don’t understand this instruction I also can’t understand the principle of if statements in this example.

Can someone explain it to me step by step please?

Advertisement

Answer

JavaScript

is simply a short way of writing

JavaScript

because the “value” of an assignment is equal to the value being assigned. Which means that max = nums[0] evaluates to the same value as nums[0]. So the line of code could be rewritten like this to make the meaning slightly more obvious:

JavaScript

And why this is done is simple: the “current minimum” and “current maximum” is often set to the first value of a non-empty list before the loop, because we know that the true minimum is at most as much as the value of the first element and the true maximum is at least as much as the value of the first element.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement