How does a For loop work?
- Control falls into the for loop. Initialization is done
- The flow jumps to Condition
- Condition is tested.
- If the Condition yields true, the flow goes into the Body
- If the Condition yields false, the flow goes outside the loop
- The statements inside the body of the loop get executed.
- The flow goes to the Updation
- Updation takes place and the flow goes to Step 3 again
- The for loop has ended and the flow has gone outside.
For Loop in Java
Loops in Java come into use when we need to repeatedly execute a block of statements. Java for loop provides a concise way of writing the loop structure. The for statement consumes the initialization, condition, and increment/decrement in one line thereby providing a shorter, easy-to-debug structure of looping. Let us understand Java for loop with Examples.
Syntax:
for (initialization expr; test expr; update exp)
{
// body of the loop
// statements we want to execute
}