Java Reference
In-Depth Information
for ( ; ; ) {
// Do something
}
for ( ; true ; ) {
// Do something
}
while ( true ) {
// Do something
}
Equivalent
Equivalent
This is better
(a)
(b)
(c)
5.8
Do the following two loops result in the same value in sum ?
Check
Point
for ( int i = 0 ; i < 10 ; ++i) {
sum += i;
}
for ( int i = 0 ; i < 10 ; i++) {
sum += i;
}
(a)
(b)
5.9
What are the three parts of a for loop control? Write a for loop that prints the num-
bers from 1 to 100 .
5.10
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, sum = 0 , count;
for (count = 0 ; count < 5 ; count++) {
number = input.nextInt();
sum += number;
}
System.out.println( "sum is " + sum);
System.out.println( "count is " + count);
}
}
5.11
What does the following statement do?
for ( ; ; ) {
// Do something
}
5.12
If a variable is declared in a for loop control, can it be used after the loop exits?
5.13
Convert the following for loop statement to a while loop and to a do-while loop:
long sum = 0 ;
for ( int i = 0 ; i <= 1000 ; i++)
sum = sum + i;
5.14
Count the number of iterations in the following loops.
int count = 0 ;
while (count < n) {
count++;
}
for ( int count = 0 ;
count <= n; count++) {
}
(a)
(b)
 
Search WWH ::




Custom Search