There are still other ways to define
powerOf2
using a for
loop. You can, for example, bring the
reassignment of the result
variable within the reassignment part of
the for
loop, joining it to the reassignment of the counter
variable. The result is a for
loop with an empty statement,
which consists of a semicolon only, in place of an ordinary statement or
block:
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; // Initialization counter != 0; // Test --counter, result = result * 2) // Reassignment ; // Empty statement return result; }}