Consider, for example, the following oddball version of powerOf2
,
in which the decrementing of the counter
variable occurs in the
Boolean expression, rather than in the normal continuation expression,
which is missing. The suffix form, counter--
, must be used,
rather than the prefix form, --counter
, because decrementing is to
be done after your program decides whether to go around the loop. Were you
to use the prefix form, your program would fail to go around the loop
enough times:
public class Demonstrate { public static void main (String argv[]) { System.out.println(powerOf2(4)); } public static int powerOf2 (int n) { int result = 1; for (int counter = n; counter-- != 0;) { result = 2 * result; } return result; }}