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

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Another important control flow mechanism <strong>in</strong> a programm<strong>in</strong>g language is loop<strong>in</strong>g.<br />

<strong>Java</strong> provides for three types of loops.<br />

While Loops<br />

The simplest k<strong>in</strong>d of loop <strong>in</strong> <strong>Java</strong> is a while loop. Such a loop tests that a certa<strong>in</strong><br />

condition is satisfied <strong>and</strong> will perform the body of the loop each time this<br />

condition is evaluated to be true. The syntax for such a conditional test before a<br />

loop body is executed is as follows:<br />

while (boolean_exp)<br />

loop_statement<br />

At the beg<strong>in</strong>n<strong>in</strong>g of each iteration, the loop tests the expression, boolean exp, <strong>and</strong><br />

then executes the loop body, loop_statement, only if this Boolean expression<br />

evaluates to true. The loop body statement can also be a block of statements.<br />

Consider, for example, a gnome that is try<strong>in</strong>g to water all of the carrots <strong>in</strong> his<br />

carrot patch, which he does as long as his water<strong>in</strong>g can is not empty. S<strong>in</strong>ce his can<br />

might be empty to beg<strong>in</strong> with, we would write the code to perform this task as<br />

follows:<br />

public void waterCarrots () {<br />

}<br />

Carrot current = garden.f<strong>in</strong>dNextCarrot ();<br />

while (!waterCan.isEmpty ()) {<br />

}<br />

water (current, waterCan);<br />

current = garden.f<strong>in</strong>dNextCarrot ();<br />

Recall that "!" <strong>in</strong> <strong>Java</strong> is the "not" operator.<br />

For Loops<br />

Another k<strong>in</strong>d of loop is thefor loop. In their simplest form, for loops provide<br />

for repeated code based on an <strong>in</strong>teger <strong>in</strong>dex. In <strong>Java</strong>, we can do that <strong>and</strong> much<br />

more. The functionality of a for loop is significantly more flexible. In particular,<br />

the usage of a for loop is split <strong>in</strong>to four sections: the <strong>in</strong>itialization, the condition,<br />

the <strong>in</strong>crement, <strong>and</strong> the body.<br />

54

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

Saved successfully!

Ooh no, something went wrong!