Challenge: Min and Max by Pointer
Completed
Complete void minMax(const vector<int>& v, int* lo, int* hi): it must store the smallest value in *lo and the largest in *hi. The starter reads the numbers and prints the result.
Input
n (1 or more), then n integers.
Output
min max on one line.
Example
Input
5 4 9 1 7 3
Output
1 9
Editor
C++
Hints
Start both *lo and *hi at the first item, v[0].
Loop over v and update them when you find a smaller or bigger value.
Solution explanation
A function can only return one value, but through pointers (or references) it can fill in as many as you need.
Show solution
#include <iostream>
#include <vector>
using namespace std;
void minMax(const vector<int>& v, int* lo, int* hi) {
*lo = v[0];
*hi = v[0];
for (int x : v) {
if (x < *lo) *lo = x;
if (x > *hi) *hi = x;
}
}
int main() {
int n;
cin >> n;
vector<int> v(n);
for (int& x : v) cin >> x;
int smallest, largest;
minMax(v, &smallest, &largest);
cout << smallest << " " << largest << "\n";
return 0;
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module