Home Segments Index Top Previous Next

307: Mainline

Suppose, for example, that you are asked to figure out the number of customers that your railroad will have at a given time if the number of customers doubles each month starting now. Plainly, the number after n months is proportional to 2n, thus requiring you to develop a function that computes the nth power of 2.

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

int power_of_2 (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;