Home Segments Index Top Previous Next

191: Mainline

Suppose, for example, that you are asked to figure out the price that a stock will have if the price doubles monthly. Plainly, the price 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;