Java Reference
In-Depth Information
33 }
34
35 // Check if the next number is prime
36 number++;
37
}
38 }
39 }
The first 50 prime numbers are
2 3 5 7 11 13 17 19 23 29
31 37 41 43 47 53 59 61 67 71
73 79 83 89 97 101 103 107 109 113
127 131 137 139 149 151 157 163 167 173
179 181 191 193 197 199 211 223 227 229
This is a complex program for novice programmers. The key to developing a programmatic
solution for this problem, and for many other problems, is to break it into subproblems and
develop solutions for each of them in turn. Do not attempt to develop a complete solution
in the first trial. Instead, begin by writing the code to determine whether a given number is
prime, then expand the program to test whether other numbers are prime in a loop.
To determine whether a number is prime, check whether it is divisible by a number between
2 and number/2 inclusive (lines 16-21). If so, it is not a prime number (line 18); otherwise, it
is a prime number. For a prime number, display it. If the count is divisible by 10 (lines 27-30),
advance to a new line. The program ends when the count reaches 50 .
The program uses the break statement in line 19 to exit the for loop as soon as the num-
ber is found to be a nonprime. You can rewrite the loop (lines 16-21) without using the break
statement, as follows:
subproblem
for ( int divisor = 2 ; divisor <= number / 2 && isPrime;
divisor++) {
// If true, the number is not prime
if (number % divisor == 0 ) {
// Set isPrime to false, if the number is not prime
isPrime = false ;
}
}
However, using the break statement makes the program simpler and easier to read in this case.
K EY T ERMS
loop body 158
nested loop 176
off-by-one error
break statement 184
continue statement
184
160
do-while loop
168
output redirection
167
for loop 171
infinite loop 160
input redirection
posttest loop
174
pretest loop
174
167
iteration
158
sentinel value
165
loop
158
while loop
158
 
 
Search WWH ::




Custom Search