Java Reference
In-Depth Information
4.24
Rewrite the programs TestBreak and TestContinue in Listings 4.12 and 4.13
without using break and continue .
4.25
After the break statement in (a) is executed in the following loop, which statement is
executed? Show the output. After the continue statement in (b) is executed in the
following loop, which statement is executed? Show the output.
for ( int i = 1 ; i < 4 ; i++) {
for ( int j = 1 ; j < 4 ; j++) {
if (i * j > 2 )
break ;
for ( int i = 1 ; i < 4 ; i++) {
for ( int j = 1 ; j < 4 ; j++) {
if (i * j > 2 )
continue ;
System.out.println(i * j);
System.out.println(i * j);
}
}
System.out.println(i);
System.out.println(i);
}
}
(a)
(b)
4.10 Case Study: Displaying Prime Numbers
This section presents a program that displays the first fifty prime numbers in five lines,
each containing ten numbers.
Key
Point
An integer greater than 1 is prime if its only positive divisor is 1 or itself. For example, 2 , 3 ,
5 , and 7 are prime numbers, but 4 , 6 , 8 , and 9 are not.
The problem is to display the first 50 prime numbers in five lines, each of which contains
ten numbers. The problem can be broken into the following tasks:
Determine whether a given number is prime.
For number = 2 , 3 , 4 , 5 , 6 , ..., test whether it is prime.
Count the prime numbers.
Display each prime number, and display ten numbers per line.
Obviously, you need to write a loop and repeatedly test whether a new number is prime. If
the number is prime, increase the count by 1 . The count is 0 initially. When it reaches 50 ,
the loop terminates.
Here is the algorithm for the problem:
Set the number of prime numbers to be printed as
a constant NUMBER_OF_PRIMES;
Use count to track the number of prime numbers and
set an initial count to 0;
Set an initial number to 2;
while (count < NUMBER_OF_PRIMES) {
Test whether number is prime;
if number is prime {
Display the prime number and increase the count;
}
Increment number by 1;
}
 
 
Search WWH ::




Custom Search