Thread: Easiest way to find the max value stored in an array

  1. #1
    Registered User
    Join Date
    Dec 2003
    Posts
    56

    Easiest way to find the max value stored in an array

    What is the easiest way to find the maximum value stored in an array and display it on the screen...
    Here's what I worked out, don't know if it works, because I don't have a compiler installed on this computer...

    Code:
    #include <iostream>
    using namespace std;
    
    void MaxElement (int Array [], int& Max);
    
    const int ArraySize = 3;
    
    int main (void)
    {
       int max;
       int Array [3]; 
    
       
    	Array [0] = 102;
    	Array [1] = 230;
    	Array [2] = 191;
    	max = Array [0];
        MaxElement (Array, max);
        cout << "Max Value: " << max << endl;
        return 0;
    }
    
    void MaxElement (int Array [], int& max)
    {
    	    for (int i = 1; i < ArraySize; i ++)
       {
          if (Array [i] > max)
             max = Array [i];
       }
    }
    Last edited by criticalerror; 01-21-2004 at 07:41 PM.

  2. #2
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    > for (i = 0; i < ArraySize; i ++)

    Slightly faster is:
    for (i = 1; i < ArraySize; i++)

  3. #3
    Registered User major_small's Avatar
    Join Date
    May 2003
    Posts
    2,787
    usually I set max to -32000 and walk through every array element... even though the way you have it is probably faster... although I don't think that speed is really a big factor in this situation...
    Join is in our Unofficial Cprog IRC channel
    Server: irc.phoenixradio.org
    Channel: #Tech


    Team Cprog Folding@Home: Team #43476
    Download it Here
    Detailed Stats Here
    More Detailed Stats
    52 Members so far, are YOU a member?
    Current team score: 1223226 (ranked 374 of 45152)

    The CBoard team is doing better than 99.16% of the other teams
    Top 5 Members: Xterria(518175), pianorain(118517), Bennet(64957), JaWiB(55610), alphaoide(44374)

    Last Updated on: Wed, 30 Aug, 2006 @ 2:30 PM EDT

  4. #4
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    Originally posted by major_small
    usually I set max to -32000 and walk through every array element... even though the way you have it is probably faster... although I don't think that speed is really a big factor in this situation...
    And what if the max int in your list is -33000?

  5. #5
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    maybe it would be better to pass the array size, and return the maximum value instead:
    Code:
    #include <iostream>
    using namespace std;
    
    int MaxElement(int Array[], int array_size);
    
    int main()
    {
    	const int array_size = 3;
    	int Array[array_size];
    
    	Array [0] = 102;
    	Array [1] = 230;
    	Array [2] = 191;
    
    	cout << "Max Value: " << MaxElement(Array, array_size); << endl;
    	return 0;
    }
    
    int MaxElement(int Array[], int array_size)
    {
    	int max = Array[0];
    	for (int i = 1; i < array_size; i++)
    	{
    		if (Array[i] > max)
    			max = Array[i];
    	}
    	return max;
    }
    Last edited by laserlight; 01-22-2004 at 12:54 AM.

  6. #6
    Senior Member joshdick's Avatar
    Join Date
    Nov 2002
    Location
    Phildelphia, PA
    Posts
    1,146
    Originally posted by swoopy
    And what if the max int in your list is -33000?
    The trick there is that the minimum value that can be stored in a signed short int is greater than -33000. If you tried to store that value in a short, you'd have an overflow error.
    FAQ

    "The computer programmer is a creator of universes for which he alone is responsible. Universes of virtually unlimited complexity can be created in the form of computer programs." -- Joseph Weizenbaum.

    "If you cannot grok the overall structure of a program while taking a shower, you are not ready to code it." -- Richard Pattis.

  7. #7
    Registered User
    Join Date
    Dec 2003
    Posts
    56
    Originally posted by laserlight
    maybe it would be better to pass the array size, and return the maximum value instead:
    Code:
    #include <iostream>
    using namespace std;
    
    int MaxElement(int Array[], int array_size);
    
    const int array_Size = 3;
    
    int main()
    {
    	const int array_size = 3;
    	int Array[array_size];
    
    	Array [0] = 102;
    	Array [1] = 230;
    	Array [2] = 191;
    
    	cout << "Max Value: " << MaxElement(Array, array_size); << endl;
    	return 0;
    }
    
    int MaxElement(int Array[], int array_size)
    {
    	int max = Array[0];
    	for (int i = 1; i < array_size; i++)
    	{
    		if (Array[i] > max)
    			max = Array[i];
    	}
    	return max;
    }
    Why would you define array_Size as a const, and then array_size as a const with the same value, and not even use array_Size? It adds unnecessary complexity. Using a global constant eliminates having to pass it from the main to the function, and eliminates alot of typing...

  8. #8
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Presumably you might need to use array_size in main() at some later point (when dealing with the array), and so you could re-use that.

    If you need to change the size of the array, then you just need to change array_size and modify the array declaration.

    At the same time, not using a global variable means that MaxElement() is not tied to that particular program.
    Maybe you decide to place various functions into header files, and include them.

    If you then decide to use this header file in some other program, you dont have to use the same variable names etc, but just need to pass the variable as an argument to the function.

  9. #9
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    hmm... my apologies there too, I didnt see that I neglected to remove your own global variable declaration when modifying your code.

    Anyway, typing more does not necessarily add to complexity.
    For example, we could then use:
    Code:
    #include <iostream>
    using namespace std;
    
    int main()
    {
    	const int array_size = 3;
    	int Array[array_size];
    
    	Array [0] = 102;
    	Array [1] = 230;
    	Array [2] = 191;
    
    	int max = Array[0];
    	for (int i = 1; i < array_size; i++)
    	{
    		if (Array[i] > max)
    			max = Array[i];
    	}
    
    	cout << "Max Value: " << MaxElement(Array, array_size); << endl;
    	return 0;
    }
    which actually is as complex in algorithmic terms as when a function is used, since it is the same algorithm.

  10. #10
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    Originally posted by joshdick
    The trick there is that the minimum value that can be stored in a signed short int is greater than -33000. If you tried to store that value in a short, you'd have an overflow error.
    Are you sure it's a short? It looks like an plain int to me.

  11. #11
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    > usually I set max to -32000 and walk through every array element
    Whereas the OP did the right thing and set max to array[0] and walked the array.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  12. #12
    Guest Sebastiani's Avatar
    Join Date
    Aug 2001
    Location
    Waterloo, Texas
    Posts
    5,708
    There is no reason to set the initial max value low like that. Just assign it the value of the first element (the OP actually did this). Giving it a signed type limits the upper ranges by half, so unless you're really needing signed data, it's just doesn't make sense to do it that way. Actually, the cononical way to do it would be to return a pointer to the max element:

    Code:
    template <class t_type>
     t_type * maxptr(t_type data[], unsigned size)
    {
     t_type * ret = data; 
    
         for(t_type * end = data+size; data != end; ++data)  {
    
             if(*data > *ret)  {
              ret = data;
           } 
        } 
     return ret;
    }

    Which you would then use to return a value:


    Code:
    template <class t_type>
     t_type max(t_type data[], unsigned size)
    {
     return *maxptr(data, size);
    }

    or change a value:


    Code:
    template <class t_type>
     void hipassfilter(t_type data[], unsigned size, t_type ceiling)
    {
        for(type_t * smp = maxptr(data, size); *smp > ceiling; smp = maxptr(data, size))  {
         *smp = ceiling;
       }
    }
    Code:
    #include <cmath>
    #include <complex>
    bool euler_flip(bool value)
    {
        return std::pow
        (
            std::complex<float>(std::exp(1.0)), 
            std::complex<float>(0, 1) 
            * std::complex<float>(std::atan(1.0)
            *(1 << (value + 2)))
        ).real() < 0;
    }

  13. #13
    Registered User
    Join Date
    Sep 2003
    Posts
    135

    Re: Easiest way to find the max value stored in an array

    Originally posted by criticalerror
    What is the easiest way to find the maximum value stored in an array and display it on the screen...
    Well, as you're clearly using C++, why not just use max_element from <algorithm>? That would appear to me to be the easiest way:

    Code:
    #include <iostream>
    #include <algorithm>
    
    using namespace std;
    
    int main()
    {
        int myArray[10] = {1,27,99,3,15,28,50,62,0,88};
        cout << *max_element(myArray, myArray+10) << endl;
    }

  14. #14
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    Or, don't use an array. Store everything in a set or multiset. Largest element (using default sorting) at any given time will always be *(--setname.end()), certainly an easy way to deal with this issue.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  15. #15
    Registered User
    Join Date
    Dec 2003
    Posts
    56

    Re: Re: Easiest way to find the max value stored in an array

    Originally posted by Omnius
    Well, as you're clearly using C++, why not just use max_element from <algorithm>? That would appear to me to be the easiest way:

    Code:
    #include <iostream>
    #include <algorithm>
    
    using namespace std;
    
    int main()
    {
        int myArray[10] = {1,27,99,3,15,28,50,62,0,88};
        cout << *max_element(myArray, myArray+10) << endl;
    }
    Ah, nice, I didn't know that function already existed. That is extremely useful. Thanks.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. need help finding the max and min of a 2d array
    By finalreign in forum C Programming
    Replies: 6
    Last Post: 04-29-2009, 11:39 AM
  2. question about multidimensional arrays
    By richdb in forum C Programming
    Replies: 22
    Last Post: 02-26-2006, 09:51 AM
  3. Hex digits stored in char array.
    By Kevinmun in forum C Programming
    Replies: 8
    Last Post: 11-18-2005, 04:05 PM
  4. Class Template Trouble
    By pliang in forum C++ Programming
    Replies: 4
    Last Post: 04-21-2005, 04:15 AM
  5. finding max values in an array
    By Unregistered in forum C Programming
    Replies: 3
    Last Post: 01-29-2002, 02:47 PM