fdunne2 said:
Hi,
Is there a function in C that returns the max value in an array? I need a function that returns the max value and the corresponding array index.
No, but it is trivial to write one.
int max_value(VALUE_TYPE * p_array,
unsigned int values_in_array,
VALUE_TYPE * p_max_value)
{
int position;
position = 0;
*p_max_value = p_array[position];
for (position = 1; position < values_in_array; ++position)
{
if (p_array[position] > *p_max_value)
{
*p_max_value = p_array[position];
break;
}
}
return position;
}
Since you didn't specify the type of the array,
I used VALUE_TYPE. If the array is of float,
then VALUE_TYPE will be float.
This could be simplified by returning the position or
index of the maximum value. The maximum value can then
be retreived from the array using the position:
maximum_value = array[position];
Besure to check the C FAQ section about arrays:
http://www.eskimo.com/~scs/c-faq/s6.html
Also, when reading float values from a binary file how do you know when you've reached the end of the file?
Regards,
Fergal.
As far as detecting end of file, check the C language FAQ:
http://www.eskimo.com/~scs/c-faq/s12.html
A very good idea is to always check the FAQ first, and
search the newsgroups before posting.
--
Thomas Matthews
C++ newsgroup welcome message:
http://www.slack.net/~shiva/welcome.txt
C++ Faq:
http://www.parashift.com/c++-faq-lite
C Faq:
http://www.eskimo.com/~scs/c-faq/top.html
alt.comp.lang.learn.c-c++ faq:
http://www.raos.demon.uk/acllc-c++/faq.html
Other sites:
http://www.josuttis.com -- C++ STL Library book