for loop in Java
Looping in programming languages is a feature that facilitates the execution of a set of instructions/functions repeatedly while some condition evaluates to true. Java provides three ways for executing the loops. While all the ways provide similar basic functionality, they differ in their syntax and condition-checking time.
- for loop: for loop provides a concise way of writing the loop structure. Unlike a while loop, a for statement consumes the initialization, condition, and increment/decrement in one line thereby providing a shorter, easy-to-debug structure of looping.
Syntax:
for (initialization condition; testing condition; increment/decrement) { statement(s) }
- Flowchart:
- Initialization condition: Here, we initialize the variable in use. It marks the start of a for loop. An already declared variable can be used or a variable can be declared, local to loop only.
- Testing Condition: It is used for testing the exit condition for a loop. It must return a boolean value. It is also an Entry Control Loop as the condition is checked prior to the execution of the loop statements.
- Statement execution: Once the condition is evaluated to be true, the statements in the loop body are executed.
- Increment/ Decrement: It is used for updating the variable for the next iteration.
- Loop termination: When the condition becomes false, the loop terminates marking the end of its life cycle.