Java Reference
In-Depth Information
This program 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
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
The outer loop, controlled by i , walks through all the integers from 1 to the value of limit. In each iteration
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 we have nested a for loop inside another for loop here, as we said at the outset, you can
nest any kind of loop inside any other. We could have written the nested loop as:
for (int i = 1; i <= limit; i++) {
factorial = 1; // Initialize factorial
int factor = 2;
while (factor <= i) {
factorial *= factor++;
}
System.out.println(i + "!" + " is " + factorial);
}
Now we have a while loop nested in a for loop. It works just as well, but it is rather more natural
coded as two nested for loops because they are both controlled by a counter.
If you have been concentrating, you may well have noticed that you don't really need
nested loops to display the factorial of successive integers. You can do it with a single
loop that multiplies the current factorial value by the loop counter. However, this
would be a very poor demonstration of a nested loop.
Search WWH ::




Custom Search