help me understand this piece of code

so i have this working piece of code that finds the max and min of an array and respectively assigns it to max and min variables
i need help understanding it, specifically why "int min" and "int max" are assigned to the array "scores[0]" and how the if else statement works

any help is appreciated :-)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
int min = scores[0];
int max = scores[0];

for (int i = 0; i < numOfJudges; i++)
{
	if (min > scores[i])
	{
	    min = scores[i];
	}
	else if (max < scores[i])
	{
	    max = scores[i];
	}
}
1
2
int min = scores[0];
int max = scores[0];

We must set some initial value for the min/max values. We can't set it to some arbitrary value, though. What if we set min to -1700000? Then we would probably never find the minimum inside the array. By initializing them to values that are in the array, we avoid that problem.

The if statements just work by saying
if the current min is greater than the value I'm looking at, change min to be that value. If the current max is less than the value I'm looking at, change max to be that value


You shouldn't need to use 'else if'. Just have two 'if' statements.
Maybe we can. If we set min to 1000000000 and max to -1000000000, that is.


Unless one sets the value to max or min for that type respectively, one can't know if there is a number that is bigger or smaller respectively. So it's easier to do what is in the OP's code and for the reasons JayhawkZombie explained.
ah okay, makes sense to me now. thank you all for your input!
closed account (48T7M4Gy)
It's very unlikely a negative score will ever occur and realistically would be trapped in major software as an exception or similar, so we can dispense with that notion.

As far as the limits for any of these numbers are concerned in order to set the ball rolling if the first in the array is not an option then arbitrary numbers are another silly notion not worth worrying about because it is easily easily dispelled by using non-arbitrary purist pedandtry thus: http://www.cplusplus.com/reference/limits/numeric_limits/

Also, provided 1000000000 is unlikely as a score and it fits the appropriate choice of variable type (int perhaps, unsigned int for purists) then I wouldn't worry too much about that either - numerical analysis is as much part of good programming practice as anything else. At worst if that number is ever exceeded by a score it can be built into the exception handling anyway.
You shouldn't need to use 'else if'. Just have two 'if' statements.
But doesn't that make the code worse instead of better? If you set the min then there really is no reason to check for the max.
Topic archived. No new replies allowed.