AlgoMaster Logo

Print All Even Numbers from 1 to N

Last Updated: June 7, 2026

easy
3 min read

Understanding the Problem

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.

Key Constraints:

  • 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.

Approach 1: Loop with Modulo

Intuition

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.

Algorithm

  1. Create an empty list to hold the result.
  2. Loop i from 1 to n inclusive.
  3. If i % 2 == 0, append i to the list.
  4. Return the list as an array.

Example Walkthrough

Input:

7
n

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].

0
2
1
4
2
6
result

Code

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.

Approach 2: Step by Two

Intuition

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.

Algorithm

  1. Create an empty list to hold the result.
  2. Start i at 2 and loop while i <= n, increasing i by 2 each step.
  3. Append i to the list on every iteration.
  4. Return the list as an array.

Example Walkthrough

Input:

7
n

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].

0
2
1
4
2
6
result

Code