Index Loop

A loop that executes when the number of iteration is explicit in the problem. The printing of numbers 1 to 10 is an example of this type of loop.

Learning Example:

Problem: Print the first five even numbers.

Analysis:

We know that the first five even numbers are the numbers 2, 6, 4, 8, 10. The problem simply says that we need to print these even numbers. If we look closer to the numbers, we will notice that there is a step of 2 from every other number. To take this step in the program, the counter function should use 2 as incrementing step to produce the even numbers.

Example Flow Chart for printing 5 first even numbers

The solution shown is the same solution in printing the numbers 1 to 10 or 1 to 1000. The things new in this solution are the incrementing step used, and the condition set to terminate the loop.

The terminating condition not only checks if the current value is less than 10 but also checks if they are the same. The flowchart terminates, if the current value of ctr greater than 10.

Code

<?php

  $ctr
= 2; /* assigned ctr = 2 , we don't want to print 0; */

 
while($ctr<=10) { // check the condition
    
print $ctr . " "; // print the value + empty space
    
$ctr = $ctr+2; // adds 2 for the value
 
}

?>

Code Evaluation [ code in action ] : Output: 
2 4 6 8 10