Categories

do and while

Do you understand the difference between do loops and while loops?  On the surface they appear very similar.

£> do{$i++}while($i -lt 10)
£> $i
10

£> $i=0
£> while($i -lt 10){$i++}
£> $i
10

BUT there is a difference

£> $i=11
£> do{$i++}while($i -lt 10)
£> $i
12

£> $i=11
£> while($i -lt 10){$i++}
£> $i

Notice the difference in the final result

A DO loop will ALWAYS execute at least once because the test is at the end.

A while loop has the test at the beginning so may not execute at all.

I’ve seen this cause people real difficulty at times so think about where you need the test to be, if the loop needs to execute at least once and what the final value of any incrementing variables should be

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>