Java Reference
In-Depth Information
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
11! is 39916800
12! is 479001600
13! is 6227020800
14! is 87178291200
15! is 1307674368000
16! is 20922789888000
17! is 355687428096000
18! is 6402373705728000
19! is 121645100408832000
20! is 2432902008176640000
How It Works
All the variables used in this example are of type long . Factorial values grow very rapidly so by using
type long you allow much larger factorials to be calculated than if you used type int . You still could
have declared factor and i as type int without limiting the size of the factorial value that the program
can produce, but the compiler would then need to insert casts to make the int values type long whenever
they were involved in an operation with a value of type long .
The outer loop, controlled by i , walks through all the integers from 1 to the value of limit . In each it-
eration of the outer loop, the variable factorial is initialized to 1, and the nested loop calculates the
factorial of the current value of i using factor as the control counter that runs from 2 to the current
value of i . The resulting value of factorial is then displayed before going to the next iteration of the
outer loop.
Although you have nested a for loop inside another for loop here, as I said at the outset, you can nest
any kind of loop inside any other. You could have written the nested loop as the following:
for (long i = 1L; i <= limit; ++i) {
factorial = 1L; // Initialize factorial
long factor = 2L;
while (factor <= i) {
factorial *= factor++;
}
System.out.println(i + "! is " + factorial);
}
Now you have a while loop nested in a for loop. It works just as well, but it is rather more naturally
coded as two nested for loops because they are both controlled by a counter.
Search WWH ::




Custom Search