Last Updated: June 7, 2026
This problem builds a list by scanning a range of numbers and keeping the ones that match a rule, the same shape as filtering records or collecting matches.
Given an integer n, walk through the whole numbers from 1 up to n and collect every one that is even. The result is an array in increasing order. For n = 10, the even numbers in range are 2, 4, 6, 8, and 10, so the answer is [2, 4, 6, 8, 10].
When n is 1, the only number in range is 1 itself, which is odd. There are no even numbers to collect, so the answer is an empty array rather than an error or a missing value.
1 <= n <= 1000 → The range is small and bounded, so a single pass is fast and a plain int holds every value without overflow.n can be 1 → The smallest input produces no even numbers. The loop must finish with an empty array instead of failing.A number is even when dividing it by 2 leaves no remainder, and the modulo operator % gives that remainder. So the test i % 2 == 0 is true for even numbers and false for odd ones.
Run through i from 1 to n and append i whenever the test passes. Visiting the range from low to high leaves the result in increasing order.
i from 1 to n inclusive.i % 2 == 0, append i to the list.Input:
Walk through i from 1 to 7. The values 1, 3, 5, and 7 fail the test i % 2 == 0, so they are skipped. The values 2, 4, and 6 pass and get appended in order. After the loop, the collected result is [2, 4, 6].
n once, so the work grows linearly with n.n / 2 numbers, which scales with n.The modulo check runs on every number, including the odd ones that get discarded. Half the iterations test a value only to skip it. The even numbers can be visited directly instead.
Even numbers form a regular pattern: 2, 4, 6, 8, and so on, each exactly 2 apart. Start at 2 and add 2 each step. Every value reached is already even, so there is no remainder test at all.
Begin at i = 2 and keep going while i is at most n, appending each value and adding 2. When n is 1, the loop starts at 2, which is already greater than 1, so it never runs and the result stays empty.
i at 2 and loop while i <= n, increasing i by 2 each step.i to the list on every iteration.Input:
Start at i = 2 and append it. Add 2 to reach 4 and append it. Add 2 to reach 6 and append it. Add 2 to reach 8, which is greater than 7, so the loop stops. No odd number was ever tested. The collected result is [2, 4, 6].
n / 2 times, which still grows linearly with n even though it skips the odd numbers.n / 2 numbers, which scales with n.