Home Segments Index Top Previous Next

300: Mainline

Suppose, for example, that you have become overweight, and you fear that your excess weight will double every year. Plainly, your excess weight after n years will be proportional to 2n. To determine your excess weight after n years, you need to develop a method 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:

Integer method definition • instance 
powerOfTwo 
  | n result | 
  n := self. 
  result := 1. 
  [n ~= 0] whileTrue: [n := n - 1.  result := 2 * result]. 
  ^ result 
Workspace
Transcript show: 4 powerOfTwo printString 
Transcript 
16 

Evidently, if you are 1 pound overweight now, and your fears are realized, you will be 16 pounds overweight in 4 years.