Home Segments Top Top Previous Next

417: Mainline

Now suppose, for example, that you want to compute the total number of viewers that a movie will have if the number doubles each month after the release date. Such a relationship cannot hold for a long time, but while it does hold, the total number of viewers after n months is proportional to 2n; thus, you need to develop a method that computes the nth power of 2.

One way to do the computation is to count down a parameter, n, to 0, multiplying a variable, result, whose initial value is 1, by 2 each time that you decrement n:

public class Demonstrate { 
 public static void main (String argv[]) { 
  System.out.println(powerOf2(4)); 
 } 
 public static int powerOf2 (int n) { 
  int result = 1;               // Initial value is 1 
  while (n != 0) { 
    result = 2 * result;        // Multiplied by 2 n times 
    n = n - 1; 
  } 
  return result; 
 } 
} 
--- Result --- 
16