2024-02-26 12:17:00 +00:00
|
|
|
#include <cassert>
|
|
|
|
#include <iostream>
|
|
|
|
#include <limits>
|
|
|
|
|
|
|
|
/* return the second-largest element of an array
|
|
|
|
* of N integer values (must contain at least two values)
|
|
|
|
*/
|
2024-02-27 17:40:25 +00:00
|
|
|
auto second_of(const int N, const int* const x) {
|
2024-02-26 12:17:00 +00:00
|
|
|
assert(N >= 2);
|
2024-02-27 17:40:25 +00:00
|
|
|
auto largest = x[0];
|
2024-02-26 12:17:00 +00:00
|
|
|
|
|
|
|
// smallest possible int value
|
2024-02-27 17:40:25 +00:00
|
|
|
auto second_largest = std::numeric_limits<int>::min();
|
2024-02-26 12:17:00 +00:00
|
|
|
|
2024-02-27 17:40:25 +00:00
|
|
|
for(auto i = 1; i < N; i++)
|
2024-02-26 12:17:00 +00:00
|
|
|
if(x[i] > largest) {
|
|
|
|
second_largest = largest;
|
|
|
|
largest = x[i];
|
|
|
|
}
|
|
|
|
else if(x[i] > second_largest)
|
|
|
|
second_largest = x[i];
|
|
|
|
return second_largest;
|
|
|
|
}
|
|
|
|
|
|
|
|
int main() {
|
2024-02-27 17:40:25 +00:00
|
|
|
constexpr auto fixed_array_size = 5;
|
2024-02-26 12:17:00 +00:00
|
|
|
constexpr int x[fixed_array_size] = {4, 0, 6, 5, 2};
|
2024-02-27 17:40:25 +00:00
|
|
|
const auto t = second_of(fixed_array_size, x);
|
2024-02-26 12:17:00 +00:00
|
|
|
std::cout << t << "\n";
|
|
|
|
}
|
2024-02-27 17:40:25 +00:00
|
|
|
|
|
|
|
/*
|
|
|
|
Which of these allowed implicit-type declarations would you actually use in programming practice?
|
|
|
|
I dont think I would use any of these. Auto takes longer time to write than int and makes the code less readable.
|
|
|
|
*/
|