Question 1
Back to Exercise
Write a function that receives an array and its size and returns the minimum and maximum through two pointer parameters.
Solution
#include <iostream>
void min_max(const int* a, int n, int* lo, int* hi) {
*lo = *hi = a[0];
for (const int* p = a + 1; p < a + n; ++p) {
if (*p < *lo) *lo = *p;
if (*p > *hi) *hi = *p;
}
}
int main() {
int data[] = {42, 17, 93, 8, 61};
int lo, hi;
min_max(data, 5, &lo, &hi);
std::cout << "min " << lo << ", max " << hi << '\n';
return 0;
}
min 8, max 93
The caller passes the addresses of lo and hi, and the function writes results through them. const int* promises the array is only read.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!