C++ bootcamp · Lab 44

Filter even values

easyVectors10 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 even values in the same order, space-separated. If none, print nothing (empty line).

Input. First line n, second line n integers.

Output. Even numbers space-separated, or empty.

Examples

Example 1
Input
5
1 2 3 4 5
Output
2 4
Example 2
Input
3
1 3 5
Output
Hint
  1. Push evens into another vector, then print.
Show correct code

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

#include <iostream>
#include <vector>

int main() {
  int n; std::cin >> n;
  std::vector<int> out;
  for (int i = 0; i < n; i++) {
    int x; std::cin >> x;
    if (x % 2 == 0) out.push_back(x);
  }
  for (size_t i = 0; i < out.size(); i++) {
    if (i) std::cout << " ";
    std::cout << out[i];
  }
  std::cout << "\n";
  return 0;
}
main.cppC++17 · g++ · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.