Official

A - Filter Editorial by en_translator


If you are new to learning programming and do not know where to start, please try Problem A “Welcome to AtCoder” from practice contest. There you can find a sample code for each language.
Also, if you are not familiar with problems in programming contests, we recommend you to try some problems in “AtCoder Beginners Selection” (https://atcoder.jp/contests/abs).


Solution 1

Read an array of length \(N\), scan its elements one by one, and print only even numbers. One can determine if an integer is even by checking if the remainder when divided by \(2\) equals \(0\).

#include <iostream>
#include <vector>

using namespace std;

int main() {
    int N;
    cin >> N;

    // array of length N
    vector<int> A(N);
    // read one by one
    for (auto&& a : A)
        cin >> a;

    for (const auto a : A) 
        // even if remainder divided by 2 is 0
        if (a % 2 == 0)
            cout << a << " ";
    cout << endl;

    return 0;
}
N = int(input())
A = list(map(int, input().split()))

for a in A:
    # even if remainder divided by 2 is 0
    if a % 2 == 0:
        print(a)

Solution 2

Alternatively, one can solve this problem by constructing an array obtained by filtering out odd numbers from \(A\).

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main(){
    int N;
    cin >> N;
    
    // array of length N
    vector<int> A(N);
    // read one by one
    for (auto&& a : A)
        cin >> a;

    // construct a new array by filtering out odds
    vector<int> B{begin(A), remove_if(begin(A), end(A), [](auto i){return i % 2 != 0;})};
    // print one by one
    for (const auto b : B)
        cout << b << " ";
    cout << endl;

    return 0;
}
N = int(input())
A = list(map(int, input().split()))

# construct a new array by filtering out odds, then print them
print(*[a for a in A if a % 2 == 0])

Solution 3

One can also solve the problem as follows: read an integer \(N\) times, and print it if the read integer is an even number.

#include <iostream>

using namespace std;

int main(){
    int N;
    cin >> N;

    // Repeat N times
    for (int i = 0; i < N; ++i){
        int a;
        cin >> a;
        // Print the read number if it is even
        if (a % 2 == 0)
            cout << a << " ";
    }
    cout << endl;

    return 0;
}

posted:
last update: