📓2.8: for Loops
Table of Contents
📖 This page is a condensed version of CSAwesome Topic 2.8
For Loops
Another type of loop in Java is a for loop. This is usually used when you know how many times you want the loop to execute. It is often a simple counter-controlled loop to do the loop body a set number of times.
Three Parts of a For Loop
A for-loop combines all 3 parts of writing a loop in one line to initialize, test condition, and change the loop control variable. The 3 parts are separated by semicolons (;):
// LOOP HEADER
for (initialize; test condition; change) {
// LOOP BODY
}
The
for-loop is like a shortcut way to write awhileloop, with all three steps that you need in one line.

Watch the following which compares a while loop and for loop line by line.
Here is a control flow diagram for a for loop:

- The code in the initialization area is executed only one time before the loop begins
- The test condition is checked each time through the loop and the loop continues as long as the condition is
true- The loop control variable change is done at the end of each execution of the body of the loop, just like a
whileloop.- When the loop condition becomes
false, execution will continue at the next statement after the body of the loop.
Two common patterns in for-loops are to count from 0 up to an number (using <) or count from 1 to a number including the number (using <=). Remember that if you start at 0 use <, and if you start at 1, use <=.
The two loops below using these two patterns both run 10 times:
// These loops both run 10 times
// If you start at 0, use <
for(int i = 0; i < 10; i++) {
System.out.println(i);
}
// If you start at 1, use <=
for(int i = 1; i <= 10; i++) {
System.out.println(i);
}
The variable
i(stands for index) is often used as a counter infor-loops.
Decrementing Loops
You can also count backwards in a loop starting from the last number and decrementing the loop counter down to 0 or 1. All 3 parts of the loop must change to count backwards including the test of when to stop.
For example,
for (int i=5; i > 0; i--)counts from 5 down to 1.
💬 DISCUSS: What do you think will happen when you run the code below? How would it change if you changed line 11 to initialize i’s value to 3?
String line1 = " bottles of pop on the wall";
String line2 = " bottles of pop";
String line3 = "Take one down and pass it around";
// loop 5 times (5, 4, 3, 2, 1)
for (int i = 5; i > 0; i--) {
System.out.println(i + line1);
System.out.println(i + line2);
System.out.println(line3);
System.out.println((i - 1) + line1);
System.out.println();
}
💻 In-Class Activity: Turtle Loops
Acknowledgement
Content on this page is adapted from Runestone Academy - Barb Ericson, Beryl Hoffman, Peter Seibel.