for( statement1; statement2; statement3;){
// code block to execute
}
statement1 : One time executed. We declare the variable here
statement2 : Condition to be checked before allowing the code block to execute. Comes out of the loop if condition is false, code block is executed if condition is true.
statement3 : Checked every time. Used for increment the variable ( step ).
Example 1
for (int i=0; i<5; i++) {
System.out.println(i);
}
Output is here
0
1
2
3
4
Example 2
for (int i=0; i<5; i=i+2) {
System.out.println(i);
}
Output is here
0
2
4
Here the i value is increased by 2 for each iteration step.
Example 3
for (int i=0; i<5; i=i+5) {
System.out.println(i);
}
Output is here
0
The loop will execute once only as the value of i will be 5 after first loop and the condition became false.
Example 4
for (int i=10; i<5; i++) {
System.out.println(i);
}
No output will be generate as the condition is false in first check. The code block inside the for loop will never be executed.
Break & Continue
Inside the loop of we use break; satement then the execution will come out of the loop.
Example using break
for (int i=0; i<5; i++) {
if ( i==3 ) {
break;
}
System.out.println(i);
}
Above code will print
0
1
2
Once i value became 3 , the if condition became true and the execution comes out of the loop. So only i value upto 2 is printed.
In the above code if System.out.println(i) is kept before the if condition check then how the output will change ?
If we use continue in place of break then the execution will skip further code ( after if ) and continue from beginning of the loop.
for (int i=0; i<5; i++) {
if ( i==3 ) {
continue;
}
System.out.println(i);
}
Output is here
0
1
2
4
Note that 3 is not included in the output as we have used if condition with continue to skip further execution. However it continues the loop after that step and prints 4.
Difference between break and continue
The execution stops and comes out of the loop once break statement is encountered. In case of continue, further execution of the code block is stopped and loop continues from starting of the loop.