19.09.2015 Views

Prentice.Hall.Introduction.to.Java.Programming,.Brief.Version.9th.(2014).[sharethefiles.com]

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

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

142 Chapter 4 Loops<br />

loop<br />

end of loop<br />

display result<br />

13<br />

14 // Keep reading data until the input is 0<br />

15 int sum = 0;<br />

16<br />

17<br />

while (data != 0) {<br />

sum += data;<br />

18<br />

19 // Read the next data<br />

20 System.out.print(<br />

21 "Enter an integer (the input ends if it is 0): ");<br />

22 data = input.nextInt();<br />

23 }<br />

24<br />

25 System.out.println("The sum is " + sum);<br />

26 }<br />

27 }<br />

Enter an integer (the input ends if it is 0):<br />

Enter an integer (the input ends if it is 0):<br />

Enter an integer (the input ends if it is 0):<br />

Enter an integer (the input ends if it is 0):<br />

The sum is 9<br />

2<br />

3<br />

4<br />

0<br />

line# data sum output<br />

12 2<br />

15 0<br />

iteration 1<br />

iteration 2<br />

iteration 3<br />

17 2<br />

22 3<br />

17 5<br />

22 4<br />

17 9<br />

22 0<br />

25 The sum is 9<br />

If data is not 0, it is added <strong>to</strong> sum (line 17) and the next item of input data is read (lines<br />

20–22). If data is 0, the loop body is no longer executed and the while loop terminates. The<br />

input value 0 is the sentinel value for this loop. Note that if the first input read is 0, the loop<br />

body never executes, and the resulting sum is 0.<br />

Caution<br />

Don’t use floating-point values for equality checking in a loop control. Because floatingpoint<br />

values are approximations for some values, using them could result in imprecise<br />

counter values and inaccurate results.<br />

Consider the following code for <strong>com</strong>puting 1 + 0.9 + 0.8 + ... + 0.1:<br />

double item = 1; double sum = 0;<br />

while ( item != 0 ) { // No guarantee item will be 0<br />

sum += item;<br />

item -= 0.1;<br />

}<br />

System.out.println(sum);

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

Saved successfully!

Ooh no, something went wrong!