### C++

Hi, I need some help with this understanding.

Write the following funtion that eturns the maximum value among the first n elements of the given array.

float max(float a[], int n)

i don't understand what they want.
You're to write a function which accepts an array of floats a[] and and integer n. The function should return the highest value in the array of floats BUT it should only consider the first part of the array up to n number of elements.

For example:

If you have an array [ 1.2, 4.7, 8.4, 3.2, 9.9] and n = 4 the function will return 8.4. 9.9 is the largest float in the array BUT it's out of range because it's the element number 5 and the limit was 4.
They want just what they said. Look at the first n elements. Find the largest. So if your array was:

1,3,8,3,1,4,2,9,6,0,5

And n was 4...

It would look at the first four:

1,3,8,3

... and find that 8 is largest and return it.

Are you allowed to use stl operators? ;) std::max_element is your friend!

 ``123456789101112131415161718192021222324252627`` ``````#include #include #include float max(float a[], int n) // The requirement you were given for this function is dangerous, you have no way to bounds check your array. Oh, and it's not const correct. { const std::vector vec(a, a + n); // Generally you should be passing references to std::containers anyway, not pointer-based arrays. return *std::max_element(vec.begin(), vec.end()); } float max_better(const std::vector& a, const int n) // It would be much better if your prof had given you this to do! { return *std::max_element(a.begin(), a.begin() + n); } int main(int argc, char** argv) { // What your prof wants your function to call float arr[] = {1.0, 3.0, 8.0, 3.0,1.0,4.0, 2.0, 9.0, 6.0, 0.0, 5.0}; std::cout << max(arr, 4) << std::endl; // What would be better std::vector vec({1.0, 3.0, 8.0, 3.0,1.0,4.0, 2.0, 9.0, 6.0, 0.0, 5.0}); std::cout << max_better(vec, 4) << std::endl; return 0; }``````

Of course, I'm guessing that you haven't gotten around to that stuff yet. ;) You'll need to have a compiler that supports the C++11 standard to handle the vector initialization suchly.
Last edited on
Topic archived. No new replies allowed.