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
Input
5 1 2 3 4 5
Output
2 4
Input
3 1 3 5
Output
Hint
- 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.