We have seen the Java program to determine if a number n is prime:
boolean isPrime; int f; isPrime = true; // Assume that n is prime... for ( f = 2; f <= n - 1 ; f++ ) { if (n % f == 0) then isPrime = false; // Now we know n is NOT prime... } |
Look closely to the loop:
for ( f = 2; f <= n - 1 ; f++ ) { if (n % f == 0) then isPrime = false; // Now we know n is NOT prime... } |
This loop runs the variable f from 2 to n-1 and test if every number is a divider of n
However... if we finds that ONE of these numbers does divide n, we can STOP THE LOOP IMMEDIATELY - because we already know that the number is not prime...
The break statement can be used to break out of the loop in this case !
boolean isPrime; int f; isPrime = true; // Assume that n is prime... for ( f = 2; f <= n - 1 ; f++ ) { if (n % f == 0) then { isPrime = false; // Now we know n is NOT prime... break; // Exit the loop NOW } } |
If the
Condition clause
is
true , then
the while body is executed.
Otherwise,
(Condition clause
is false ),
then the
while statement
is terminated.
If the
Condition clause
is
true , then
the for body is executed.
Otherwise,
(Condition clause
is false ),
then the
for statement
is terminated.
We have seen such a program before, now we will write one using the continue statement
boolean isPrime; int f, n, N; System.out.println(2); // Print 2 - it's the only even prime for ( n = 3; n <= N ; n++ ) { if ( n % 2 == 0 ) continue; // Skip the rest of the for-body // From this point on, the statements are only // executed for ODD values !!! isPrime = true; // Assume that n is prime... for ( f = 3; f <= n - 1 ; f++ ) { if (n % f == 0) then isPrime = false; // Now we know n is NOT prime... } if ( isPrime ) System.out.println( n + " is a prime number"); } |
Any program that uses break or continue statements can be re-written without using them.