Min and max values of array

the array is
int i, min_val, max_val;

1
2
3
4
5
6
7
8
9
10
11
int nums [10];
    nums [0]= 10;
    nums[1]=18;
    nums[2]=75;
    nums[3]=0;
    nums[4]=1;
    nums[5]=56;
    nums[6]=100;
    nums[7]=12;
    nums[8]=-19;
    nums[9]=88;


the code for finding the minimum and maximum values I don't understand

min_val=max_val=nums[0]; /* Does this mean that min_val and max_val have been assigned 10?*/

1
2
3
4
5
for (i=1l i<10; i++){
if (nums[i] < min_val) min_val= nums[i]
if (nums[i] > max_val) max_val= nums [i]

}



I don't understand how these code for the minimum and maximum values.
/* Does this mean that min_val and max_val have been assigned 10?*/


Yes.

1
2
3
4
5
6
for (i=0; i<10; i++){   // start at nums[0], for all terms in the array
    if (nums[i] < min_val) min_val= nums[i];    // if the current term is lower than the registered lowest value, 
                                                // set the current term to be the lowest registered value
    if (nums[i] > max_val) max_val= nums [i];   // if the current term is greater than the registered largest value, 
                                                // set the current term to be the largest registered value
}
There's a error in your code.
for (i= 1; i<10; i++)\\It was 11, it should be 1
Here's the explanation of what's going on:
First min_val and max_val are assigned the value 10.
Then the program will go into the loop.
There it will check that if num[1] is less than min_val. If it is, then num[1] will be less than num[0]. Hence num[1] will be the minimum value for now.
This will happen in the case of maximum value as well.

I hope that explains it.

EDIT:
@toexii: No need to start the loop with 0 because both the members have the value of num[0]
Last edited on
Anon1010 wrote:
min_val=max_val=nums[0]; /* Does this mean that min_val and max_val have been assigned 10?*/
Yes it does.

The code iterates through all 10 array elements checking if the value it in the current element is more/less than the current value for min_val/max_val, if it is then it takes on the value of the current element.

If you can't read code like this I strongly recommend you complete at least a few more tutorials before continuing.

You can find some good tutorials here: http://www.cplusplus.com/doc/tutorial/

Good luck.
Last edited on
Ahh I see; thanks guys. And Ink2019, this is the arrays section of a tutorial.
@toexii: No need to start the loop with 0 because both the members have the value of num[0]


Yea I realized that later, but it doesn't hurt either, and mostly I iterate through an entire array, so I just left it there for the sake of habit, but you're right.
Anon1010 wrote:
And Ink2019, this is the arrays section of a tutorial.
I'm not quite sure what you mean, but you will find a section on arrays in that link I posted earlier.
Topic archived. No new replies allowed.