Java - for Loop
The for loop is a control flow statement bundled with initialization, conditional expression, increment / decrement
Statements in a shortened way and it will execute the block of statement as long as the
specified conditional expression is valid (i.e., true).
Moreover it also supports the array iteration, it will iterate the array untill the end of record gets reach.
Example: #1 - Simple for Loop
Print the number from 1 to 5 using for loop
Java Input Screen
class ControlFlowStatement {
public static void main(String[] args) {
for(int counter = 1; counter <= 5; counter++) {
System.out.println(counter);
}
}
}
Example: #2 - Iterate over an array or iterable using for Loop
Print an array elements using for loop
Java Input Screen
class ControlFlowStatement {
public static void main(String[] args) {
int[] arr = new int[]{ 1,2,3,4,5};
for(int i : arr) {
System.out.println(i);
}
}
}
Thousands Lived without Love, but not without water. So SAVE WATER.
Example: #3 - Iterate over an array with temporary variable using for Loop
Print an array elements using for loop
Java Input Screen
class ControlFlowStatement {
public static void main(String[] args) {
int[] arr = new int[]{ 1,2,3,4,5};
for (int i = 0; i < arr.length; i++) {
int j = arr[i];
System.out.println(j);
}
}
}
Thousands Lived without Love, but not without water. So SAVE WATER.
Java for Loop with break Statement
The break statement is a termination statement, once the break
statement encountered in a for loop, immediately it will terminate the looping execution and
it return backs to the main statement execution.
Example: #4 - for Loop with break Statement
Terminate the for loop once the console printed the number 3 using the
break statement.
Java Input Screen
class ControlFlowStatement {
public static void main(String[] args) {
for(int counter = 1; counter <= 5; counter++) {
System.out.println(counter);
// Terminate the execution once counter reached 3
if(counter == 3) {
break;
}
}
}
}
Thousands Lived without Love, but not without water. So SAVE WATER.
Java while Loop with continue Statement
The continue statement is a skipping statement of a current iteration, once the continue
statement encountered in a for loop, immediately it will skip the current iteration and
it will continue the rest of the operation till the conditional expression is true.
Example: #5 - for Loop with continue Statement
Skip the for loop once the counter has reached the value 3 using the
continue statement.
Java Input Screen
class ControlFlowStatement {
public static void main(String[] args) {
for(int counter = 1; counter <= 5; counter++) {
// skips the iteration once counter reached 3
if(counter == 3) {
continue;
}
System.out.println(counter);
}
}
}
BBMINFO