< Previous | Contents | Next >

Using for Loops

You met one type of loop in Chapter 2the while loop. Well, its time to meet anotherthe for loop. Like its cousin the while loop, the for loop lets you repeat a section of code, but for loops are particularly suited for counting and moving through a sequence of things (like the items in an RPG characters inventory).


81

82 Chapter 3 n For Loops, Strings, and Arrays: Word Jumble


Heres the generic form of for loop:

for (initialization; test; action) statement;

initialization is a statement that sets up some initial condition for the loop. (For example, it might set a counter variable to 0.) The expression test is tested each time before the loop body executes, just as in a while loop. If test is false, the program moves on to the statement after the loop. If test is true, the program executes statement. Next, action is executed (which often involves incrementing a counter variable). The cycle repeats until test is false, at which point the loop ends.


 

Introducing the Counter ProgramCounting with for LoopsUsing Empty Statements in for LoopsNesting for Loops