Java Reference
In-Depth Information
do
sum += i; // Add the current value of i to sum
while(++i <= limit);
Of course, you could still put the braces in if you want. I advise that you always use brackets in your
loops even when they are only a single statement. There are often several ways of writing the code to
produce a given result, and this is true here - we could also move the incrementing of the variable i
back inside the loop and write it as:
do
sum += i++; // Add the current value of i to sum
while (i <= limit);
Note the semi-colon after the while condition is present in each version of the loop. This is part of the
loop statement so you must not forget to put it in. The primary reason for using this loop over the
while loop would be if you want to be sure that the loop code always executes at least once.
Nested Loops
You can nest loops of any kind one inside another to any depth. Let's look at an example where we 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 it can be a very useful value. For instance, 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
Our example will calculate the factorial of every integer from 1 up to a given limit. Enter the following
code with the two for loops:
public class Factorial {
public static void main(String[] args) {
long limit = 20; // to calculate factorial of integers up to this value
long factorial = 1; // factorial will be calculated in this variable
// Loop from 1 to the value of limit
for (int i = 1; i <= limit; i++) {
factorial = 1; // Initialize factorial
for (int factor = 2; factor <= i; factor++) {
factorial *= factor;
}
System.out.println(i + "!" + " is " + factorial);
}
}
}
Search WWH ::




Custom Search