Answer the question
In order to leave comments, you need to log in
How can you calculate the maximum and minimum values of an array?
I'm currently learning about arrays and came across such a problem as the minimum and maximum value of an array. As a result, based on various examples, I came up with the following code (part, c[i] is an array):
int max = 0;
int min = 0;
int max_index = 0;
int min_index = 0;
for(int i = 0; i < 20; ++i)
{
if(max < c[i])
{
max = c[i];
max_index = i;
}
if(min > c[i])
{
min = c[i];
min_index = i;
}
}
Answer the question
In order to leave comments, you need to log in
In short, you don't need to store the minimum and maximum values separately, because they are always accessible by index in the array. Another thing is that you don't have these indexes before you start iterating through the array, you simply have nowhere to get them from. This moment determines the correct initial state in solving your problem. The absence of this moment also leads to the fact that your code is now working incorrectly.
You only need the indexes of those elements that you consider to be the minimum and maximum.
size_t min_value_index = 0;
size_t max_value_index = 0;
0
order to initially designate the first element of the array as both the minimum and the maximum at the same time. This is how I define the initial state of the algorithm. for( size_t index = 1; index < stream_length; ++index )
{
// ...
}
for( size_t index = 1; index < stream_length; ++index )
{
if( stream[ index ] < stream[ min_value_index ] )
{
min_value_index = index;
}
if( stream[ index ] > stream[ max_value_index ] )
{
max_value_index = index;
}
}
min_value_index
index of the minimum value of the array will be guaranteed to lie in, and the max_value_index
index of the maximum value will lie in the index. The most correct is:
cout << *min_element(begin(c), end(c)) << endl;
cout << *max_element(begin(c), end(c)) << endl;
std::partial_sort(begin(с), begin(с) + 1, end(с));
auto m = с.front();
std::partial_sort(begin(с), begin(с) + 1, end(с), greater<long>());
auto M = с.front();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question