Home Segments Index Top Previous Next

385: Mainline

You can also add the numbers in an Array instance by arranging for integers between 1 and the size of the array to be assigned to a parameter. Then you can use the parameter as an array index inside a block.

Thus, you have the following alternative to the approach in Segment 383 for adding up the numbers in an array. Note that the size message determines the size of the array:

Array method definition • instance 
sumUp 
  | sum | 
  sum := 0. 
  1 to: self size 
    do: [:index | sum := sum + (self at: index)]. 
  ^ sum 
Workspace
Transcript show: (Array with: 570 with: 720 with: 640 with: 720) 
                 sumUp printString 
Transcript 
2650