19.09.2015 Views

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

Create successful ePaper yourself

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

144 Chapter 4 Loops<br />

4.4 Suppose the input is 2 3 4 5 0. What is the output of the following code?<br />

import java.util.Scanner;<br />

public class Test {<br />

public static void main(String[] args) {<br />

Scanner input = new Scanner(System.in);<br />

int number, max;<br />

number = input.nextInt();<br />

max = number;<br />

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

number = input.nextInt();<br />

if (number > max)<br />

max = number;<br />

}<br />

}<br />

}<br />

System.out.println("max is " + max);<br />

System.out.println("number " + number);<br />

4.5 What is the output of the following code? Explain the reason.<br />

int x = 80000000;<br />

while (x > 0)<br />

x++;<br />

System.out.println("x is " + x);<br />

Key<br />

Point<br />

4.3 The do-while Loop<br />

A do-while loop is the same as a while loop except that it executes the loop body<br />

first and then checks the loop continuation condition.<br />

The do-while loop is a variation of the while loop. Its syntax is:<br />

do-while loop<br />

do {<br />

// Loop body;<br />

Statement(s);<br />

} while (loop-continuation-condition);<br />

Its execution flowchart is shown in Figure 4.2.<br />

The loop body is executed first, and then the loop-continuation-condition is evaluated.<br />

If the evaluation is true, the loop body is executed again; if it is false, the do-while<br />

loop terminates. The difference between a while loop and a do-while loop is the order in<br />

which the loop-continuation-condition is evaluated and the loop body executed. You<br />

can write a loop using either the while loop or the do-while loop. Sometimes one is a more<br />

convenient choice than the other. For example, you can rewrite the while loop in Listing 4.5<br />

using a do-while loop, as shown in Listing 4.6.<br />

LISTING 4.6<br />

TestDoWhile.java<br />

1 import java.util.Scanner;<br />

2<br />

3 public class TestDoWhile {

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

Saved successfully!

Ooh no, something went wrong!