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.

public void eatApples (Apples apples) {<br />

}<br />

numApples = apples.getNumApples ();<br />

for (<strong>in</strong>t x = 0; × < numApples; ×++) {<br />

}<br />

eatApple (apples.getApple (×));<br />

spitOutCore ();<br />

In the <strong>Java</strong> example above, the loop variable x was declared as <strong>in</strong>t x = 0.<br />

Before each iteration, the loop tests the condition " x < numApples" <strong>and</strong><br />

executes the loop body only if this is true. F<strong>in</strong>ally, at the end of each iteration the<br />

loop uses the statement x++ to <strong>in</strong>crement the loop variable x before aga<strong>in</strong> test<strong>in</strong>g<br />

the condition.<br />

Incidentally, s<strong>in</strong>ce 5.0, <strong>Java</strong> also <strong>in</strong>cludes a for-each loop, which we discuss <strong>in</strong><br />

Section 6.3.2.<br />

Do-While Loops<br />

<strong>Java</strong> has yet another k<strong>in</strong>d of loop besides the for loop <strong>and</strong> the st<strong>and</strong>ard while<br />

loop—the do-while loop. The former loops tests a condition before perform<strong>in</strong>g<br />

an iteration of the loop body, the do-while loop tests a condition after the loop<br />

body. The syntax for a do-while loop is as shown below:<br />

do<br />

loop_statement<br />

while (boolean_exp)<br />

Aga<strong>in</strong>, the loop body statement, loop_statement, can be a s<strong>in</strong>gle statement or a<br />

block of statements, <strong>and</strong> the conditional, boolean_exp, must be a Boolean<br />

expression. In a do-while loop, we repeat the loop body for as long as the<br />

condition is true each time it is evaluated.<br />

Consider, for example, that we want to prompt the user for <strong>in</strong>put <strong>and</strong> then do<br />

someth<strong>in</strong>g useful with that <strong>in</strong>put. (We discuss <strong>Java</strong> <strong>in</strong>put <strong>and</strong> output <strong>in</strong> more detail<br />

<strong>in</strong> Section 1.6.) A possible condition, <strong>in</strong> this case, for exit<strong>in</strong>g the loop is when the<br />

user enters an empty str<strong>in</strong>g. However, even <strong>in</strong> this case, we may want to h<strong>and</strong>le<br />

56

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

Saved successfully!

Ooh no, something went wrong!