23.11.2014 Views

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

Data Structures and Algorithms in Java[1].pdf - Fulvio Frisone

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Def<strong>in</strong><strong>in</strong>g a For Loop<br />

Here is the syntax for a <strong>Java</strong> for loop:<br />

for (<strong>in</strong>itialization; condition; <strong>in</strong>crement)<br />

loop_statement<br />

where each of the sections <strong>in</strong>itialization, condition, <strong>and</strong> <strong>in</strong>crement can be empty.<br />

In the <strong>in</strong>itialization section, we can declare an <strong>in</strong>dex variable that will only exist<br />

<strong>in</strong> the scope of the for loop. For example, if we want a loop that <strong>in</strong>dexes on a<br />

counter, <strong>and</strong> we have no need for the counter variable outside of the for loop,<br />

then declar<strong>in</strong>g someth<strong>in</strong>g like the follow<strong>in</strong>g<br />

for (<strong>in</strong>t counter = 0; condition; <strong>in</strong>crement)<br />

loop_statement<br />

will declare a variable counter whose scope is the loop body only.<br />

In the condition section, we specify the repeat (while) condition of the loop. This<br />

must be a Boolean expression. The body of the for loop will be executed each<br />

time the condition is true when evaluated at the beg<strong>in</strong>n<strong>in</strong>g of a potential<br />

iteration. As soon as condition evaluates to false, then the loop body is not<br />

executed, <strong>and</strong>, <strong>in</strong>stead, the program executes the next statement after the for<br />

loop.<br />

In the <strong>in</strong>crement section, we declare the <strong>in</strong>crement<strong>in</strong>g statement for the loop. The<br />

<strong>in</strong>crement<strong>in</strong>g statement can be any legal statement, allow<strong>in</strong>g for significant<br />

flexibility <strong>in</strong> cod<strong>in</strong>g. Thus, the syntax of a for loop is equivalent to the<br />

follow<strong>in</strong>g:<br />

<strong>in</strong>itialization;<br />

while (condition) {<br />

}<br />

loop_statement;<br />

<strong>in</strong>crement;<br />

except that, <strong>in</strong> <strong>Java</strong>, a while loop cannot have an empty Boolean condition,<br />

whereas a for loop can. The follow<strong>in</strong>g example shows a simple for loop <strong>in</strong><br />

<strong>Java</strong>:<br />

55

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!