Java Reference
In-Depth Information
✓
✓
4.6
Suppose the input is
2 3 4 5 0
. What is the output of the following code?
Check
Point
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;
do
{
number = input.nextInt();
if
(number > max)
max = number;
}
while
(number !=
0
);
System.out.println(
"max is "
+ max);
System.out.println(
"number "
+ number);
}
}
4.7
What are the differences between a
while
loop and a
do-while
loop? Convert the
following
while
loop into a
do-while
loop.
Scanner input =
new
Scanner(System.in);
int
sum =
0
;
System.out.println(
"Enter an integer "
+
"(the input ends if it is 0)"
);
int
number = input.nextInt();
while
(number !=
0
) {
sum += number;
System.out.println(
"Enter an integer "
+
"(the input ends if it is 0)"
);
number = input.nextInt();
}
Key
Point
Often you write a loop in the following common form:
i = initialValue;
// Initialize loop control variable
while
(i < endValue) {
// Loop body
...
i++;
// Adjust loop control variable
}
A
for
loop can be used to simplify the preceding loop as:
for
(i = initialValue; i < endValue; i++) {
// Loop body
...
}