Maximum and Minimum in C++ | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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?

18th Nov 2018, 1:38 PM
Martina
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 <numeric> library which computes the sum of the given initial value of the sum and the elements in the range [first, last). Example: #include <iostream> #include <algorithm> #include <numeric> #include <vector> using namespace std; int main () { vector<int> 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<double>(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
18th Nov 2018, 2:27 PM
Babak
Babak - avatar
+ 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
18th Nov 2018, 2:28 PM
KrOW
KrOW - avatar
+ 1
Thanks ^^
20th Nov 2018, 11:45 AM
Martina