next up previous
Next: 2.2 Tracing the Execution Up: 2 Recursion Previous: 2 Recursion


2.1 Summing the First n Positive Integers

The first example uses a recursive definition to sum the integers 1 to k. The divide and conquer solution has two cases.

  1. Base case.

    When there are no integers to be added, the result should be zero.

  2. Smaller, but identical, problem.

    When there are k (k>0) integers, the solution can be written as k+sum(k-1).

Following are the Scheme and J programs for summing the integers 1 to k.

(define sum
  (lambda(n)
    (if (= n 0)
      0
      (+ n (sum (- n 1))))))

Program sum (Scheme Version)

sum =: monad define script
if. y. = 0
  do. 0
  else. y. + sum y. - 1
end.
)

Program sum (J Version)


next up previous
Next: 2.2 Tracing the Execution Up: 2 Recursion Previous: 2 Recursion
2002-11-26