For loop
- for loop is a repetition control structure that allows you
to efficiently write a loop that needs to be executed a
specific number of times
Engr. Babila
Syntax
for (statement 1; statement 2; statement 3) { // code block to
be executed }
Statement 1 is executed (one time) before the execution of the code block.
Statement 2 defines the condition for executing the code block.
Statement 3 is executed (every time) after the code block has been executed.
Syntax of for loop:
for(initialization; condition ; increment/decrement) {
statement(s); }
OUTPUT:
for (int i = 0; i < 5; i++) 0
1
{ System.out.println(i); } 2
3
4
Flow chart
For-Each Loop
There is also a "for-each" loop, which is used exclusively to loop through
elements in an array:
Syntax
for (type variableName : arrayName) { //
code block to be executed }
public class Main {
public static void main(String[] args) { OUTPUT:
Volvo
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (: cars) { BMW
Ford
System.oString i ut.println(i);
} Mazda
}
}
Java Break
The break statement can also be used to jump out of a loop.
OUTPUT:
for (int i = 0; i < 10; i++) {
0
if (i == 4) { break; } 1
System.out.println(i); } 2
3
Java Continue
continue statement breaks one iteration (in the loop), if a specified condition
occurs, and continues with the next iteration in the loop.
OUTPUT:
0
for (int i = 0; i < 10; i++) { 1
if (i == 4) { continue; } 2
3
System.out.println(i); } 5
6
7
8
9
https://www.w3schools.com/java/java_for_loop.asp
https://beginnersbook.com/2015/03/for-loop-in-java-with-
example/