// programming iterative vs recursive // use array // use index to divide array // an array has index [0..N], its size is N+1 ax = array 100 N = 10 // ------- sum of an array ---------- to suma x | s i = s = 0 for i 0 N s = s + x[i] s to sumrec x i = if i == N x[i] else x[i] + (sumrec x (i+1)) to testsum | i = for i 0 N ax[i] = i print suma ax nl print sumrec ax 0 nl // -------- max of an array -------- to maxa x | i m = m = x[0] for i 1 N if m < x[i] m = x[i] m to max2 a b = if a > b a else b to maxrec x a b | c = if a == b // one item x[a] else c = (a + b)/2 // divide in the middle max2 (maxrec x a c) (maxrec x (c+1) b) to testmax | i = for i 0 N ax[i] = i ax[5] = 88 print maxa ax nl print maxrec ax 0 N nl // ----- multiply by add repeat add ----------- to mul a b | i s = s = 0 for i 1 b s = s + a s to mulrec a b = if b == 0 0 else if b == 1 a else a + (mulrec a (b-1)) to mulreca2 a b c = {} to mulreca a b = mulreca2 a b 0 to mulreca2 a b c = if b == 0 c else mulreca2 a (b-1) (c+a) to testmul = print mul 5 4 nl print mulrec 5 4 nl print mulreca 5 4 nl to main = testmul // 19 Jan 2010