• Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint

6.8. for

The for statement provides a looping construct that is often more convenient than the while statement. The for statement takes advantage of a pattern common to most loops (including the earlier while loop example). Most loops have a counter variable of some kind. This variable is initialized before the loop starts and is tested as part of the expression evaluated before each iteration of the loop. Finally, the counter variable is incremented or otherwise updated at the end of the loop body, just before expression is evaluated again.

The initialization, the test, and the update are the three crucial manipulations of a loop variable; the for statement makes these three steps an explicit part of the loop syntax. This makes it especially easy to understand what a for loop is doing and prevents mistakes such as forgetting to initialize or increment the loop variable. The syntax of the for statement is:


PREVIEW

                                                                          

Not a subscriber?

Start A Free Trial


  
  • Creative Edge
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint