Java Reference
In-Depth Information
5.2
What is wrong if guess is initialized to 0 in line 11 in ListingĀ 5.3?
5.3
How many times are the following loop bodies repeated? What is the output of each
loop?
int i = 1 ;
while (i < 10 )
if (i % 2 == 0 )
System.out.println(i);
int i = 1 ;
while (i < 10 )
if (i % 2 == 0 )
System.out.println(i++);
int i = 1 ;
while (i < 10 )
if ((i++) % 2 == 0 )
System.out.println(i);
(a)
(b)
(c)
5.4
Suppose the input is 2 3 4 5 0 . What is the output of the following code?
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int number, max;
number = input.nextInt();
max = number;
while (number != 0 ) {
number = input.nextInt();
if (number > max)
max = number;
}
System.out.println( "max is " + max);
System.out.println( "number " + number);
}
}
5.5
What is the output of the following code? Explain the reason.
int x = 80000000 ;
while (x > 0 )
x++;
System.out.println( "x is " + x);
5.3 The do-while Loop
A do-while loop is the same as a while loop except that it executes the loop body
first and then checks the loop continuation condition.
Key
Point
The do - while loop is a variation of the while loop. Its syntax is:
do-while loop
do {
// Loop body;
Statement(s);
} while (loop-continuation-condition);
Its execution flowchart is shown in FigureĀ 5.2.
The loop body is executed first, and then the loop-continuation-condition is evalu-
ated. If the evaluation is true , the loop body is executed again; if it is false , the do - while
 
 
 
Search WWH ::




Custom Search