Quick Reach
For loop video of this tutorial
Structure of the for loop
The for loop of Java is the way to execute the specified block of code again and again to the given number of times. The Java for loop iterates over a given sequence.
Following is the structure of the for loop:
for ( initialization; condition; update_the_counter){
//Code to be executed;
}
Where:
- The first parameter in the for loop sets a counter initial value.
- The second parameter, which is a condition, tells until when code should be executed.
- The third parameter is the increment or decrement operator.
- Execute the code within the for loop enclosed in the curly braces.
The flow of Java For loop
First of all, the initialization step is executed and then flow is moved to the condition that will be evaluated. If the condition is true the code in curly braces will execute.
After execution of the code, the flow will be back to “update_the_counter” part. After that, the condition is evaluated again and keeps on executing the code in curly braces until the condition is false.
As the condition becomes false the execution gets out of the for loop to the next line of code.
Example of using for loop
In this example, we will declare an integer variable a and assign it an initial value. After that, a for loop of Java is used where we will increment that variable by 1 for each iteration and display its value on the screen.
The iteration will go on until the value of variable a reaches 11.
See the example online by clicking the link or image below:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
public class loop_example {
public static void main(String []args) {
int a;
a=1;
for (a=1; a<=10; a++){
System.out.println(“Current value of a = “ + a); // Java loop example
}
}
}
|
Experience this online
The output will be:
Current value of a = 1
Current value of a = 2
Current value of a = 3
Current value of a = 4
Current value of a = 5
Current value of a = 6
Current value of a = 7
Current value of a = 8
Current value of a = 9
Current value of a = 10
Further Reading: The while loop | The do while loop | Java foreach
Leave A Comment?