user5425294
user5425294

Reputation:

Finding the smallest value in an array

So I'm having some trouble with something. I have to create a function that will find the smallest number in an array. I know of one way to do it, using an overkill amount of if/else if, which won't do any good if the array size changes. I know using a for loop should do the trick but I can't figure out how to write it. Any push in the right direction would be greatly appreciated.

#include <iostream>
using namespace std;

int findLowest(int[]);

int main()
{
    int AR[5] = {4, 87, 1, -3, 78};
    cout << findLowest(AR);

    return 0;
}

int findLowest(int AR[])
{

     return lowest;
}

Upvotes: 0

Views: 179

Answers (4)

BufferOverflow
BufferOverflow

Reputation: 543

Instead of defining your own function to find the smallest number in your array, why do you not use the standard std::min_element function to do it for you? Create a std::vector object from the array, and let the min_element function do the job for you.

#include <algorithm>
#include <cstdlib>
#include <iostream>
#include <vector>

#define ARRAY_SIZE 5

int main ( int argc, char **argv )
{
        int ar [ ARRAY_SIZE ] = {4, 87, 1, -3, 78};

        std::vector<int> arVector ( ar, ar + ARRAY_SIZE );

        std::cout << *std::min_element ( arVector.begin ( ), arVector.end ( )) << std::endl;

        return EXIT_SUCCESS;
}

Output:

-3

Upvotes: 0

CroCo
CroCo

Reputation: 5741

#include <iostream>
#include <cassert>
using namespace std;

int findLowest(int ar[], const int& SIZE)
{
    assert(("Error: the size of the array is zero. Make sure that ", SIZE > 0));

    int lowest = ar[0];

    for(int i=0; i<SIZE;i++)
    {
        if(lowest > ar[i])
            lowest = ar[i];
    }
    return lowest;
}

int main()
{
    const int SIZE(5);
    int AR[5] = {11, 12, 10, 14, 15};
    cout << findLowest(AR,SIZE);

    return 0;
}

Upvotes: 0

Red Alert
Red Alert

Reputation: 3816

template<size_t N>
int findLowest(int (&ar)[N])
{
    return *std::min_element(std::begin(ar), std::end(ar));
}

Note the usage of a template to make sure we get the size information from the caller.

Upvotes: 3

Alex Reynolds
Alex Reynolds

Reputation: 96984

If you can change the function signature and include a header file that specifies general limits, you could do the following, which reads through the array in one pass:

#include <climits>
...

/* assumes AR_size > 0 */
int findLowest(int AR[], int AR_size)
{
     int lowest = INT_MAX;
     for (i = 0; i < AR_size; ++i) {
         lowest = (AR[i] < lowest) ? AR[i] : lowest;
     }
     return lowest;
}

Upvotes: 3

Related Questions