**New course!**Every coder should learn

**Generative AI!**

+ 3

# Write program for find second maximum number.

i want a program for find second maximum number from unsorted array..

5 Answers

+ 4

see my codes you will find the solution

+ 3

ok i am search it in your codes.

+ 3

Your question is pretty general, so here's a generic C++ function I cooked up that should do the trick:
template <typename Iter>
Iter find_second_largest(Iter begin, Iter end) {
Iter max = end;
Iter max2 = end;
for (Iter i = begin; i != end; ++i)
if (max == end || *i > *max) {
max2 = max;
max = i;
}
return max2;
}
Example usage:
int main() {
std::array<int, 5> arr = { 4, 2, 10, 3, 14 };
// Outputs 10!
std::cout << *find_second_largest(arr.begin(), arr.end());
return 0;
}
In general, what you want to do is keep track of TWO maximum values. Every time you update the max, set the second max to the old value of max.
For example, say our current maximum is 10, and we come across 20. Now our current maximum is 20, and our second maximum is 10. Keep doing that as you traverse the collection.
Edit: I added a revised version of this function to my code library if you want to play around with it.

+ 2

thanks @Squidy but your logic is complex to understand.

+ 1

thanks @saqib ali your program is easy to understand