Using while with a Counter

Oct 06, 2009 Author: strumica

A counter is used to associate a number with each execution of a loop. Mostof the time, this number simply increments from 0 or 1 to higher valuesuntil the loop finishes.

However, the number can also decrement, change bysome multiple, or have a function applied to it to generate a new value.

A counter is usually also a type of sentinel value. That is, the counter is generally used in the condition that determines when the looping stops.

Using a counter, it’s possible to create sequentially numbered lists as outputor perform calculations with a list of values.

 A while with a counter takes a few extra lines of code to initialize thecounter before the loop and modify it for each successive execution of theloop.

A while with a counter generally looks like this:

$counter = 0;
while ($counter < 10)
code to execute;
// increment counter
This would result in the code executing 10 times. For each successive execution,the value of $counter would be one higher. So, the values would be 0, 1, 2, …, 8, 9.

views 6027
  1. Add New Comment