The for loop is used to iterate over a range of values to repeat a sequence of code.
How Does the for Loop Work in Java?
The for loop, like the while loop, will repeat a block of code. However, instead of relying on one condition, the for loop has an iteration loop that contains three components and will determine whether the code will be run. These three components are listed below:
1. Initialization
This part of the for loop will set the starting value of the iteration loop. You will often see an initialization like i=0;.
2. Condition
A boolean condition is used to determine the loop's endpoint. Each time the loop completes a cycle, the condition is tested, and if it's false, it will exit the loop.
3. Iteration
This determines how the control variable, which was set in the initialization, is changed with each iteration. You will often see an iteration like i++.
How to Write a for Loop in Java?
The general syntax of a for is as follows:
for(initialization; condition; iteration){
statement;
}
Infinite for Loop
Each portion of the for loop is optional, so leaving all of them out would result in an infinite loop.
// infinite loop because there is no condition to terminate execution
for( ; ; ){
//executable code
}
Like with while loops, an infinite loop is almost always a bad idea and should be avoided!
Java for Loop Example 1
The following for loop prints out a message followed by the count variable. The loop executes as long as count is less than 5. Test it out to see for yourself.
public class Main{
public static void main(String[] args){
// "count = count + 1" can also be written as "count++"
for(int count = 0; count < 5; count = count + 1){
System.out.println("This is count: " + count);
}
}
}
Java for Loop Example 2
The following for loop is the same as above, except it counts backward.
public class Main {
public static void main(String[] args){
for(int count = 5; count >= 0; count = count - 1){
// "count = count - 1" can also be written as "count--"
System.out.println("This is count: " + count);
}
}
}
Experiment with For Loops
Use the code editor below to experiment with various for loops.
class Main {
public static void main(String[] args) {
// please use a for loop below to print out every number
// between 0 & 100 (inclusive)
// please use another for loop below to print out every
// odd number between 100 and 0 in descending order
// please demonstrate "nesting" two for loops below
// keep your code above this line
}
}
Summary: Java for Loop
- The
forloop statement repeatedly executes a block of code - The execution of a
forloop is dependent on an iteration loop defined by an initialization, condition, and iteration - Infinite
forloops should be avoided
Syntax
Here's the syntax for the for loop, where you can substitute the variables starting with your_ with your values.
for(your_initialization; your_condition; your_iteration){
//your_code
}