C++ bootcamp · Lab 45

Min and max

easyVectors8 minLesson: Vectors

Read the question, write C++ on the right, then Run or Check.

QuestionHint and solution stay closed until you open them

Read n then n integers. Print the minimum and maximum separated by a space.

Input. n, then n integers.

Output. min max

Examples

Example 1
Input
4
3 1 8 2
Output
1 8
Example 2
Input
1
5
Output
5 5
Hint
  1. Track running min and max while reading.
Show correct code

Peek only after you have tried. You can still Check your own version.

#include <iostream>
#include <algorithm>

int main() {
  int n; std::cin >> n;
  int x; std::cin >> x;
  int lo = x, hi = x;
  for (int i = 1; i < n; i++) {
    std::cin >> x;
    lo = std::min(lo, x);
    hi = std::max(hi, x);
  }
  std::cout << lo << " " << hi << "\n";
  return 0;
}
main.cppC++17 · g++ · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.