Java Reference
In-Depth Information
WARNING Whenitcomestocontrollingaloop,neveruseteststhatdependonanexactvalue
for a floating-point variable.
Nested Loops
You can nest loops of any kind one inside another to any depth. Let's look at an example where you can use
nested loops.
A factorial of an integer, n , is the product of all the integers from 1 to n . It is written as n !. It may seem a
little strange if you haven't come across it before, but the factorial of an integer is very useful for calculating
combinations and permutations of things. For example, n ! is the number of ways you can arrange n different
things in sequence, so a deck of cards can be arranged in 52! different sequences. Let's try calculating some
factorial values.
TRY IT OUT: Calculating Factorials
This example calculates the factorial of every integer from 1 up to a given limit. Enter the following
code:
public class Factorial {
public static void main(String[] args) {
long limit = 20L;
// Calculate factorials of integers up
to this value
long factorial = 1L;
// A factorial will be stored in this
variable
// Loop from 1 to the value of limit
for (long i = 1L; i <= limit; ++i) {
factorial = 1L;
// Initialize factorial
for (long factor = 2; factor <= i; ++factor) {
factorial *= factor;
}
System.out.println(i + "! is " + factorial);
}
}
}
Factorial.java
This program produces the following output:
Search WWH ::




Custom Search