For Loops
Introduction: 4.2.0
- Usually used when you know how many times a loop should execute
- Often a
counter-controlled loop
- Similar to
repeat(n)
blocks in other languages
- Often a
Three Parts of a For Loop: 4.2.1
- Combines all 3 parts of writing a loop into one line
- initialize, test, and change the loop control variable
- 3 parts are seperated by semicolons
- each part of the declaration are optional
- the semicolons are not!
- initialize, test, and change the loop control variable
for (initialize; test condition; change) {
loop body;
}
for (int i = 0; i <= 10; i++) {
System.out.println("i is less than or equal than 10! i="+i);
}
- Kind of a shortcut way of writing a while loop
flow for a For loop
- code initialization area is executed once before the loop begins
- test condition is checked every iteration
- loop continues as long as it evaluates true
- loop control variable change happens at the end of each iteration
- after the test condition evaluates false, execution continues at the next statement
common design patterns
- count from 0 and use
<
- count from 1 and use
<=
- Need to include the number to get the expected number of iterations
for (int i = 0; i < 10; i++) {
System.out.println(i);
}
String[] myPets = {
"fido",
"tabby",
"bubbles",
"louie"
};
System.out.println("These are all my pets, in the order I got them!");
// counting from 1 makes things easier sometimes
for (int i = 1; i <= myPets.length; i++) {
System.out.println("#%d: %s".formatted(i, myPets[i-1]));
// I don't have to do math to get numbers for the pet; we're already counting from 1
}
Decrementing loops: 4.2.2
- Can also count backwards
- all parts of the loop need to change
String[] myPets = {
"fido",
"tabby",
"bubbles",
"louie"
};
System.out.println("These are all my pets, youngest to oldest!");
for (int i=myPets.length-1; i > 0; i--) {
System.out.println(myPets[i]);
}
Turtle loops: 4.2.3
- We can use loops to draw things with a turtle
- This repeats code automatically instead of manually writing lines again
Summary: 4.2.5
- 3 parts to a loop header
- initialization
- test condition
- an increment/decrement statement to change the control variable
- in a for loop, the initialization statement is only executed once
- the variable being initialized is the
loop control variable
- the variable being initialized is the
- the increment or decrement statement is executed after the entire loop body
- A for loop can bw rewritten as a while loop and vice versa
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.
This was adapted from the CS Awesome curriculum, which was created by
Barbara Ericson, Beryl Hoffman, and many other CS Awesome contributors. All rights reserved.
CS Awesome is licensed under CC BY-NC-SA 4.0.