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

Advertisements
This entry was posted in Powershell Basics. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s