0

# Maximum and Minimum in C++

Can someone please explain to me how do I make an algorithm to find the maximum, minimum and average of n numbers in C ++ without using arrays?

3 Answers

+ 5

std::minmax_element ¹ from the <algorithm> library which finds the smallest and greatest element in the range [first, last) and std::accumulate ² from the library which computes the sum of the given initial value of the sum and the elements in the range [first, last).
Example:
#include
#include
#include
#include
using namespace std;
int main () {
vector v = {5, -10, 0, 8, 1, -9, 12, 20};
auto low_high = minmax_element(v.begin(), v.end());
double avg = accumulate(v.begin(), v.end(), 0) / static_cast(v.size());
cout << "min value: " << *low_high.first << endl;
cout << "max value: " << *low_high.second << endl;
cout << "avg: " << avg << endl;
}
Output:
min value: -10
max value: 20
avg: 3.375
EDIT: I figured late that the OP wanted it without array but I remember it was without using loop! 8D
______
¹ https://en.cppreference.com/w/cpp/algorithm/minmax_element
² https://en.cppreference.com/w/cpp/algorithm/accumulate

+ 5

Use 4 ints: one track current min, one track max, one track current input count, and last track the sum of inputs... At any input reading set the min as this if this is smaller that current, same for max but if its greater, increment count var and add to sum var... At end you will have to divide sum by count for get average

+ 1

Thanks ^^

Hot today

Application RAM usage

1 Votes

Pandas Problem

4 Votes

About Java McQ

0 Votes

Showing errors!

2 Votes

Q. Anna is 18 years old

0 Votes