impera Open Impera

AP Computer Science A · Selection and iteration

while and for loops

1while loops

A while loop repeats its body as long as its condition is true:

int n = 1;
while (n <= 5) {
    System.out.print(n + " ");
    n++;
}
// prints 1 2 3 4 5

The condition is checked before each iteration, so the body may run zero times. Something inside the loop must eventually make the condition false, or you get an infinite loop.

Use while when you do not know in advance how many times to repeat, e.g. "keep halving until the value is below 1".

Check yourself

If a while condition is false at the start, the body runs:

  • Twice

  • Once

  • Zero times

  • Forever

Show the answer

Zero times

Checked first.

2for loops

A for loop puts the initialisation, condition and update in one header:

for (int i = 0; i < 5; i++) {
    System.out.print(i + " ");
}
// prints 0 1 2 3 4

Order of execution: initialise once → check condition → body → update → check condition → …

Any for loop can be rewritten as a while loop and vice versa. The loop variable i declared in the header exists only inside the loop.

The order a for loop runs: initialise, test, body, update, test again

Check yourself

How many times does for (int i = 3; i < 10; i += 2) run?

  • 5

  • 4

  • 7

  • 3

Show the answer

4

i = 3, 5, 7, 9.

3Standard loop algorithms

  • Sum / average: int sum = 0; for (...) sum += value;
  • Count matches: if (condition) count++;
  • Find min/max: start with the first value, update when a better one appears.
  • Digits of a number: while (n > 0) { int d = n % 10; n /= 10; }
  • String traversal: for (int i = 0; i < s.length(); i++) with s.substring(i, i + 1).
Worked example

sum of digits of 4,072.

  1. d = 2, sum = 2, n = 407.
  2. d = 7, sum = 9, n = 40.
  3. d = 0, sum = 9, n = 4.
  4. d = 4, sum = 13, n = 0. Loop ends: 13.
Check yourself

What does this compute? int c = 0; for (int i = 1; i <= 20; i++) if (i % 3 == 0) c++;

  • 20, the number of times the loop runs

  • 3, the value that i is divided by

  • 6, the multiples of 3 from 1 to 20

  • 7, the multiples of 3 from 0 to 20

Show the answer

6, the multiples of 3 from 1 to 20

3, 6, 9, 12, 15, 18.

4Off-by-one errors and tracing

Off-by-one errors are the most common loop bug: running one time too many or too few.

  • i < n runs for $i = 0$ to $n - 1$ ($n$ times).
  • i <= n runs for $i = 0$ to $n$ ($n + 1$ times).
  • For strings, i <= s.length() with substring(i, i + 1) throws an exception on the last pass.

Tracing: make a table of the variables after each iteration. This is the best way to answer "what is printed" questions.

Check yourself

for (int i = 0; i <= 10; i++) runs how many times?

  • 11

  • 9

  • 10

  • 12

Show the answer

11

0 through 10.

5Going deeper: counting iterations, standard algorithms and loop bugs

The two loops are interchangeable.

for (int i = 0; i < n; i++) {
    // body
}

is the same as

int i = 0;
while (i < n) {
    // body
    i++;
}

Use for when the number of repetitions is known in advance; while when the loop continues until something happens.

Order of events in a for loop: initialize once; test the condition; run the body; update; test again. The loop variable's final value is the first one that fails the test.

Counting iterations

  • for (int i = 0; i < n; i++): n times (i = 0 … n − 1).
  • for (int i = 1; i <= n; i++): n times.
  • for (int i = a; i < b; i++): b − a times.
  • for (int i = a; i <= b; i++): b − a + 1 times.
  • With a step: for (int i = 0; i < 20; i += 3) takes i = 0, 3, 6, 9, 12, 15, 18: 7 times.
  • Halving: for (int i = n; i > 0; i /= 2) runs about log₂ n + 1 times. For n = 16: 16, 8, 4, 2, 1: 5 times.
Worked example

how many times does "hi" print?

for (int k = 3; k <= 15; k += 4) {
    System.out.println("hi");
}
  1. k = 3, 7, 11, 15 pass the test.
  2. k = 19 fails.
  3. Four times.

Tracing with a table: one column per variable, one row per pass.

Worked example

what is printed?

int n = 1;
int count = 0;
while (n < 50) {
    n = n * 3;
    count++;
}
System.out.println(n + " " + count);
  1. n = 3, count = 1.
  2. n = 9, count = 2.
  3. n = 27, count = 3.
  4. n = 81, count = 4. Now 81 < 50 is false.
  5. Output: 81 4. The loop body runs to the end even though n passed 50 partway.

Standard algorithms

Accumulate a sum, then average (cast before dividing):

int sum = 0;
for (int i = 1; i <= n; i++) {
    sum += i;
}
double avg = (double) sum / n;

Find a maximum (start from the first value, or from Integer.MIN_VALUE, never from 0 if values may be negative).

Count how many satisfy a condition.

Test divisibility (is n prime?):

boolean prime = n > 1;
for (int d = 2; d < n; d++) {
    if (n % d == 0) {
        prime = false;
    }
}

Process digits: use n % 10 and n /= 10 while n > 0.

Sentinel loop: repeat until a special value appears.

Loop bugs

  • Infinite loop: the condition never becomes false, usually because the update is missing or moves the wrong way (i-- with i < n).
  • Off-by-one: one pass too many or too few. Check the first and last values of the loop variable by hand. i <= arr.length runs one step past the end.
  • Loop never runs: the condition is false at the start.
  • A semicolon after the header: for (...); has an empty body.
  • Using the loop variable afterward: a variable declared in the for header does not exist after the loop.

Worked example (find the bug): intended to print 1 to 5.

int i = 1;
while (i < 5) {
    System.out.println(i);
    i++;
}
  1. Prints 1, 2, 3, 4.
  2. When i = 5 the test i < 5 fails.
  3. Fix: i <= 5.

Early exit: a return inside a loop ends the method at once, which is the usual way to write a search:

for (int i = 0; i < arr.length; i++) {
    if (arr[i] == target) {
        return i;
    }
}
return -1;

The return -1 must come after the loop, not in an else inside it: otherwise the method gives up after checking only the first element.

Common mistakes

  • Wrong boundary (< against <=).
  • Forgetting to update the loop variable in a while loop.
  • Initializing a maximum to 0.
  • Returning "not found" inside the loop.
  • Declaring the accumulator inside the loop, resetting it each pass.
Check yourself

How many times does the body of for (int i = 10; i > 0; i -= 3) execute?

  • 10

  • 4

  • 5

  • 3

Show the answer

4

i takes the values 10, 7, 4 and 1; then −2 fails the test.

6For top marks

  • Choose for when the number of iterations is known; while when it depends on a condition.
  • Initialise accumulators before the loop.
  • Check the first and last iterations explicitly for off-by-one errors.
  • Number of iterations of for (int i = a; i < b; i++) is b − a.
Example

reverse a string:

String rev = "";
for (int i = s.length() - 1; i >= 0; i--) {
    rev += s.substring(i, i + 1);
}
Check yourself

What is printed? int k = 10; while (k > 1) { k /= 2; System.out.print(k + " "); }

  • 10 5 2 1

  • 5 2 1

  • 5 2 1 0

  • 5 2

Show the answer

5 2 1

Prints after halving.

Now test yourself

This lesson has a 8-question quiz and 5 exam-style questions with mark schemes in Impera. Free, with your progress saved.

Practise in Impera