question regarding arrays
May 5, 2015 at 3:26am UTC
Hello,
so in an array, what is the formula or syntax in order to find/output the biggest and the smallest number?
thank you,
May 5, 2015 at 3:55am UTC
The easiest way is to just use the standard library. In the header
<algorithm> you'l find functions called
min_element and
max_element , which you can use:
1 2 3 4 5 6 7
#include <algorithm>
// ...
int arr[10] = {0, 4, 2, 6, 12, -5, 13, 8, 2, 4};
std::cout << *std::min_element(arr, arr + 10) << std::endl;
std::cout << *std::max_element(arr, arr + 10) << std::endl;
-5
13
Last edited on May 5, 2015 at 3:56am UTC
May 5, 2015 at 9:21am UTC
thank you NT3
and how do you get the Average?
thanks,
May 5, 2015 at 11:53am UTC
Add them all together and divide by size.
To add an array together, you can either just write a loop yourself or use
std::accumulate :
1 2 3 4 5 6 7 8 9
#include <numeric>
// ...
int arr[10] = {0, 4, 2, 6, 12, -5, 13, 8, 2, 4};
int sum = std::accumulate(arr, arr + 10, 0);
// Cast to double to get floating point averages
std::cout << static_cast <double >(sum) / 10.0 << std::endl;
4.6
Last edited on May 5, 2015 at 11:53am UTC
Topic archived. No new replies allowed.