Conveniently, you can both declare and initialize the counter
variable in the for
statement itself, thus producing a more compact
for
loop:
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; counter = counter - 1) { result = 2 * result; } return result; } }