Public Group

find the max value

This topic is 4466 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

Hi I was wondering is there a build in max function in C that return the max value and index of an array? If there is none, does anyone know the best way to create one? Thanks in advance for your help

Share on other sites
int max_value = 0;
int max_index = -1;

for (int x = 0 ; x < ARRAY_MAX ; x++)
{
If (array[x] > max_value)
{
max_value = array[x];
max_index = x;
}
}

Now you have the max_value and max value index.

Share on other sites
int index = -1;int value = 0x80000000; // lowest possible valuefor (int i=0; i<length; i++){    if (array > value)    {        value = array;        index = i;    }}

if the array is sorted, then this reduces to:

int index = length-1;int value = array[index];

;-)

Share on other sites
Beat ya Fred.. :)

theTroll

Share on other sites
Damnit :)

But mine works for arrays of negative numbers, too ;)

Share on other sites
You should initialize with the first value in the array, rather than some arbitrary constant.

int* find_max(int* array, unsigned int length){   int* max = (length != 0) ? array : NULL;   for(int* ptr=array; ptr != array+length; ++ptr)      if(*ptr > *max) max = ptr;   return max;}

In C++, you'd just use std::max_element from <algorithm>.

Share on other sites
Quote:
 HiI was wondering is there a build in max function in C that return the max value and index of an array?If there is none, does anyone know the best way to create one?

Is this all you need or do you need to look at this image?
http://i35.photobucket.com/albums/d196/tometoyou/containerchoice.png

Share on other sites
What you want is a container class.

In general, vectors (some languages call them Array Lists or just Lists) are "smart" arrays which usually have the following properties:

* They remember their size information (also called the "length").

* They are dynamic (they can expand and contract).

* They often perform bounds checking (throwing an exception when you try to access before 0 or beyond the length).

* They are almost always what you want to use. Arrays make for many more errors.

Share on other sites
The OP mentioned C, not C++.

Share on other sites
Quote:
 Original post by FrunyThe OP mentioned C, not C++.

true, but this still stands as you create the structures.
Quote:
 Is this all you need or do you need to look at this image?

1. 1
2. 2
Rutin
19
3. 3
4. 4
5. 5

• 14
• 30
• 13
• 11
• 11
• Forum Statistics

• Total Topics
631782
• Total Posts
3002324
×