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.
- 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.
for (int i = 0; i < 4; i++) {
System.out.print(i + " ");
}
System.out.println();Output0 1 2 3Counting 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++.
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();Output10 10 4 10 6 2
for and while are interchangeable
Any for loop can be rewritten as a while loop by moving the parts:
Codeint i = 0; // initialization
while (i < 3) { // condition
System.out.print(i);
i++; // update
}
System.out.println();Output012- 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
forloop can be written as awhileloop, and the reverse.
for (int i = 0; i < n; i++)runs n times;i <= nruns 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.
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