Back to Beginner: I/O, Arithmetic, Loops
Q26Question 26 of 30

Print Even Numbers: print all even integers between 1 and N

Key Concepts
  • The stepping approach starts at 2 and increments by 2, only ever touching even numbers: N/2 iterations, no modulo test.
  • The filter approach loops from 1 to N and prints only when i % 2 == 0: twice the iterations and a modulo check each.
  • The stepping approach is more efficient and simpler to reason about for fixed-stride generation.
  • The filter approach is better when the selection rule is more complex than a fixed stride.
  • For N < 2, the result is empty because there are no even numbers in that range.
  • In production, collect values into a list and return it rather than printing, for testability.

Definition

Print evens by starting at 2 and stepping by 2 up to N: more efficient than walking all numbers and filtering with modulo.
  • Stepping approach – start at 2, increment by 2: for (int i = 2; i <= n; i += 2). Only touches evens.
  • Filter approach – loop 1 to N, print when i % 2 == 0. Double the iterations.
  • Efficiency – stepping does N/2 iterations with no test; filter does N iterations with a modulo each.
  • Empty result – for N < 2, no even numbers exist in range.
  • Testability – collect into a list and return rather than printing.

National Bank of India schedules an audit of even-numbered accounts up to account N. The system lists 2, 4, 6, 8, 10 for N = 10, stepping by two so it never wastes time on odd accounts.

Understanding the Concepts

What is the problem?

Print all even integers between 1 and N inclusive. For N = 10, output: 2 4 6 8 10.

How do you implement the stepping approach?

JAVA
package com.bank.service;

import java.util.ArrayList;
import java.util.List;

public class EvenLister {

    public static List<Integer> evensUpTo(int n) {
        List<Integer> evens = new ArrayList<>();
        for (int i = 2; i <= n; i += 2) {
            evens.add(i);
        }
        return evens;
    }

    public static void main(String[] args) {
        System.out.println("Evens up to 10: " + evensUpTo(10));
        System.out.println("Evens up to 1:  " + evensUpTo(1));
    }
}
TEXT
Evens up to 10: [2, 4, 6, 8, 10]
Evens up to 1:  []

How does the filter approach compare?

JAVA
public static List<Integer> evensFilter(int n) {
    List<Integer> evens = new ArrayList<>();
    for (int i = 1; i <= n; i++) {
        if (i % 2 == 0) evens.add(i);
    }
    return evens;
}

| Feature | Stepping | Filter |
|---|---|---|
| Iterations | N/2 | N |
| Per-iteration test | none | modulo |
| Flexibility | fixed stride only | any predicate |
| Readability | very clear | general pattern |

What are edge cases?

  • N = 0 or N = 1: no even numbers, empty result.
  • N = 2: single even number [2].
  • N is even: N itself is included.
  • N is odd: the largest even is N-1.
  • Negative N: no even numbers between 1 and a negative number, empty result.

Why return a list instead of printing?

Returning a list makes the method unit-testable. A test can assert the exact contents. Printing is a side effect that belongs at the call site.

JAVA
assertEquals(List.of(2, 4, 6, 8, 10), EvenLister.evensUpTo(10));
assertEquals(List.of(), EvenLister.evensUpTo(1));

What about Java Streams?

The IntStream.iterate method with a stepping stride mirrors the loop approach directly. The filter variant mirrors the filter approach.

JAVA
import java.util.stream.IntStream;
import java.util.List;
import java.util.stream.Collectors;

// Stepping with IntStream.iterate (Java 9+)
List<Integer> evens = IntStream.iterate(2, i -> i <= 10, i -> i + 2)
    .boxed()
    .collect(Collectors.toList());
// [2, 4, 6, 8, 10]

// Filter with IntStream.rangeClosed
List<Integer> evens2 = IntStream.rangeClosed(1, 10)
    .filter(i -> i % 2 == 0)
    .boxed()
    .collect(Collectors.toList());
// [2, 4, 6, 8, 10]

How is this used in a banking batch?

At National Bank of India, even-numbered accounts are assigned to batch A and odd-numbered ones to batch B for overnight reconciliation. The EvenLister produces the worklist for batch A.

JAVA
List<Integer> batchA = EvenLister.evensUpTo(5000);
System.out.println("Batch A accounts: " + batchA.size()); // 2500

What are common mistakes?

JAVA
// Wrong: starting at 1 and stepping by 2 (generates odds!)
for (int i = 1; i <= n; i += 2) // 1, 3, 5, 7, 9

// Correct: start at 2 for evens
for (int i = 2; i <= n; i += 2) // 2, 4, 6, 8, 10

What about performance for very large N?

For very large N, materializing the entire list may consume too much memory. Use IntStream.iterate(2, i -> i <= n, i -> i + 2) and process elements lazily with forEach instead of collecting. This keeps memory at O(1) while still visiting all even numbers.

What should a senior engineer know?

The stepping loop is the same pattern behind many stride-based algorithms: even numbers (stride 2), every 5th element (stride 5), or sampling every 100th record. A senior engineer generalizes the pattern and parameterizes the stride. In a banking audit worklist at National Bank of India, even-numbered accounts were selected up to a cutoff, and the list was passed to the next processing stage.

What are common interview follow-up questions?

  • How would you print odd numbers instead? (Start at 1, step by 2.)
  • How would you sum the even numbers instead of listing them?
  • What is the closed-form sum of evens from 2 to N?

Visual Overview

DIAGRAM
  i = 2
    │
    ▼
  ┌───────────┐
  │ i <= N ?  │──No──→ End
  └────┬──────┘
       │ Yes
       ▼
  Print i
  i = i + 2
       └──→ back to i <= N?

  For N=10: prints 2, 4, 6, 8, 10

Key Takeaway

Printing the even numbers up to N is best done with a stepping approach: start at 2, increment by 2, and collect each value. This only touches even numbers and does about N/2 iterations with no per-element test. The filter approach loops from 1 to N and checks each with modulo, doing twice the work, but is useful when the selection rule is more complex.

For N less than 2, the result is empty because there are no even numbers in that range. Collecting into a list and returning it rather than printing makes the method testable and composable.

In a banking project at National Bank of India, even-numbered accounts were selected for an audit worklist up to a cutoff. The stepping loop produced the list efficiently, and the returned collection was passed to the next processing stage.

Remember one sentence: start at 2 and step by 2 to generate only evens, avoiding the overhead of checking every number with modulo.

---

Share
Use ← → arrow keys to navigate