Java Reference
In-Depth Information
System.out.println(i + "!" + " is " + factorial);
}
}
}
If you run this it will produce the output:
1! is 1
2! is 2
3! is 6
4! is 24
5! is 120
6! is 720
7! is 5040
8! is 40320
9! is 362880
10! is 3628800
12! is 479001600
14! is 87178291200
16! is 20922789888000
18! is 6402373705728000
20! is 2432902008176640000
How It Works
The outer loop has the label OuterLoop . In the inner loop, when the condition in the if statement is
true , the labeled continue is executed causing an immediate transfer to the beginning of the next
iteration of the outer loop.
In general, you can use the labeled continue to exit from an inner loop to any enclosing outer loop,
not just the one immediately enclosing the loop containing the labeled continue statement.
Using the break Statement in a Loop
We have seen how to use the break statement in a switch block. Its effect is to exit the switch block
and continue execution with the first statement after the switch. You can also use the break statement
to break out from a loop when you need. When break is executed within a loop, the loop ends
immediately and execution continues with the first statement following the loop. To demonstrate this we
will write a program to find prime numbers. In case you have forgotten, a prime number is an integer
that is not exactly divisible by any number less than itself, other than 1 of course.
Try It Out - Calculating Primes I
Start with the main() method in the class Primes , and declare nValues and isPrime . Then start a
for loop that will loop through all integers from 2 to nValues .
public class Primes {
public static void main(String[] args) {
int nValues = 50; // The maximum value to be checked
boolean isPrime = true; // Is true if we find a prime
Search WWH ::




Custom Search