In bowling one often uses ten pins positioned on four rows. How many pins are needed for five rows, six rows, or n rows (where n is a positive integer)?
The below procedure calculates the number of pins needed for n rows recurssively.
(define (number-of-pins-rec n)(if(= n 1) n (+ n (number-of-pins-rec(- n 1)))))> (number-of-pins-rec 2)
3
> (number-of-pins-rec 4)
10
> (number-of-pins-rec 5)
15
> (number-of-pins-rec 6)
21
The procedure in a iterative process.
(define (number-of-pins-it-help n sum count)(if (> count n)
sum
(number-of-pins-it-help n
(+ sum count)
(+ count 1))))
(define (number-of-pins-it n)
(number-of-pins-it-help n 0 1))
> (number-of-pins-it 3)
6
> (number-of-pins-it 4)
10
> (number-of-pins-it 5)
15
> (number-of-pins-it 6)
21
> (number-of-pins-it 7)
28
No comments:
Post a Comment