ACSA Exam Prep
Unit 2 · Selection and Iteration · Topic 2.8

for Loops

Skill 2.ASkill 3.ASkill 3.D

Big idea: A for loop packs the counter setup, the test, and the update into one line. Use it when you know how many times to repeat.

Learning objectives
  • Develop code to represent iterative processes using for loops and determine the result of these processes.

Anatomy of a for loop

  • Initialization (int i = 0) runs once, first.
  • Condition (i < 4) is checked before each pass.
  • Update (i++) runs after each full pass of the body.
Code
for (int i = 0; i < 4; i++) {
  System.out.print(i + " ");
}
System.out.println();
Output
0 1 2 3

Counting iterations

for (int i = a; i < b; i++) runs b - a times. With <= it runs b - a + 1 times. Updates don't have to be i++.

Code
int c1 = 0, c2 = 0, c3 = 0;
for (int i = 0; i < 10; i++) c1++;
for (int i = 1; i <= 10; i++) c2++;
for (int i = 0; i < 10; i += 3) c3++;
System.out.println(c1 + " " + c2 + " " + c3);
for (int i = 10; i > 0; i -= 4) System.out.print(i + " ");
System.out.println();
Output
10 10 4
10 6 2

for and while are interchangeable

Any for loop can be rewritten as a while loop by moving the parts:

Code
int i = 0;            // initialization
while (i < 3) {       // condition
  System.out.print(i);
  i++;                // update
}
System.out.println();
Output
012
Key points
  • Header: initialization; condition; update.
  • Initialization runs once; the condition is checked before each pass; the update runs after each pass.
  • The variable set up in the header is the loop control variable.
  • Any for loop can be written as a while loop, and the reverse.
Watch out
  • for (int i = 0; i < n; i++) runs n times; i <= n runs n + 1 times.
  • A variable declared in the for header doesn't exist after the loop.
  • Changing the loop variable inside the body as well as in the header makes tracing tricky; watch for it.
Quick check
How many times does this run? for (int k = 5; k <= 20; k += 5)
Show answer
4 times: k = 5, 10, 15, 20.
What is printed?
for (int i = 1; i < 20; i *= 2) System.out.print(i + " ");
Show answer
1 2 4 8 16