Account
Categories

For-loop


Definition:

The for loop firstly checks the condition.

If the condition is true, the loop inside the curly braces executes.

After that, an increment or a decrement will occur.

Then again, the loop rechecks the condition.

If the condition is false, the loop exits from the curly braces.

Now you will clearly understand the code logic with the help of the flowchart.

For Loop Flowchart:

First step: → You will write the program
      |
Second step: → Now you will set the initialization (start value)
      |
Then you will check the condition (true/false)

If you find the condition "True", then
      |
    Execute Code
      |
   Do the increment/decrement
      |
 Go back and check the condition again

If the condition is "False", then
      |
   Stop the loop
      |
   End the program

Syntax:

for (initialization; condition; increment/decrement) {

    // The code is written here and executed to produce the output as long as the condition is true.

}

Example:

<?php
$a = 2;
$b = 4;
$sum = 0;

for ($i = 1; $i <= 1; $i++) {
  $sum = $a + $b;
  echo " $sum";
}
?>

Output:

6