So I creating a program that calculate the mean, median and range of 5 chosen numbers, but I wanted to calculate the min and max number.
I had no idea how to do, but I've got this c++ app and it had a bit of code that will do the job. So I got it.
1 2 3 4 5 6 7 8 9
int min = userNumbers, max = userNumbers;
for(int i = 0; i<5; i++)
if(userNumbers[i] > max)
max = userNumbers[i];
if(userNumbers[i] < min)
min = userNumbers[i];
I just want help understanding it, I don't want a piece of code in my program that I don't understand.
All I know it that the for loop cycles through the my array I created int userNumbers; and then assign the max and min number. But how does it know when its found the largest and smallest number in the array?
Low is correct. The program won't stop just because it's found the highest and lower values. It'll stop because the code doesn't tell it to continue (if that makes sense) then it will do whatever the code tells it to do next. In this example the code tell the computer to keep comparing each element of the array to the first element and if it's greater or lesser assign the current element to max or min. Once it has done this 5 times it stops and will continue with whatever code is after the for statement. It's up to you, as the programmer, to ensure that this is sufficient to do what you want. Just glancing at the code I'd say it works fine.