TOPIC 2.9 · STUDY

Implementing Selection and Iteration Algorithms

Students combine if with while or for to run a small algorithm on int values. Typical patterns test even or odd with % 2, count how many values in a range meet a test, and accumulate a running total. Loop bounds decide which integers are visited.

2.9.A

Selection inside iteration

A selection-and-iteration algorithm walks through a sequence of int values and uses an if to decide what to do with each one. The loop visits the values; the if filters or updates. Stay with scalar int counters. Do not reach for arrays or ArrayList here.

Three patterns show up again and again. First, even or odd: n % 2 == 0 means even, and a nonzero remainder means odd. Second, counting in a range: start a counter at 0, visit every integer from a low bound through a high bound with while or for, and increment only when the if test succeeds. Third, accumulating a total: start total at 0 and add each kept value with total += n (or add a digit peeled with % 10). The same loop can hold both a count and a sum when you need both.

int n = 7;
int kept = 0;
int total = 0;
while (n <= 12) {
    if (n % 2 == 0) {
        kept++;
        total += n;
    }
    n++;
}
System.out.print(kept);
System.out.print(" ");
System.out.print(total);

Trace the loop with n starting at 7. The condition n <= 12 lets the body run for 7, 8, 9, 10, 11, and 12. For 7, 9, and 11 the remainder of % 2 is not 0, so those odds are skipped. For 8, 10, and 12 the if body runs: kept becomes 1, then 2, then 3, and total becomes 8, then 18, then 30. After n advances to 13 the while stops. The console shows 3 30: three even values whose sum is 30.

A counter walks 7 through 12. Pale boxes mark odds that the if skips; green boxes mark evens that are kept and added.

The counter advances one step at a time. Green cells pass the even test and feed kept and total; pale cells do not.

Key points

  • Combine if with while or for to filter or update as you visit values.
  • n % 2 == 0 identifies even; a nonzero remainder identifies odd.
  • A count starts at 0 and increments only when the if test succeeds.
  • A total starts at 0 and grows with += on each kept value.
  • Use int scalars only; arrays and ArrayList are not part of this topic.

The loop bounds decide which values are visited; an off-by-one bound drops or adds a value.

Practice this topic