Home Segments Top Top Previous Next

422: Mainline

Now, you can define the powerOf2 method using a for loop instead of a while loop. The initialization expression, counter = n, assigns the value of the parameter n to counter. Then, as long as the value of counter is not 0, the value of result, whose initial value is 1, is multiplied by 2, and the value of counter is decremented by 1:

public class Demonstrate { 
 public static void main (String argv[]) { 
  System.out.println(powerOf2(4)); 
 } 
 public static int powerOf2 (int n) { 
  int counter, result = 1; 
  for (counter = n; counter != 0; counter = counter - 1) { 
    result = 2 * result; 
  } 
  return result; 
 } 
}