SCHEME CODE
write a Scheme program to calculate the sum of even numbers up to a given number n using both
tail recursion and normal recursion:
Tail Recursion
Tail recursion optimizes memory by making the recursive call the last operation. Here's the
implementation:
(define (sum-even-tail n acc)
(if (<= n 0)
acc
(if (even? n)
(sum-even-tail (- n 1) (+ acc n))
(sum-even-tail (- n 1) acc))))
;; Example usage
(sum-even-tail 10 0) ; Output: 30
Normal Recursion
This implementation doesn't optimize memory as the recursive call is not the last operation:
(define (sum-even n)
(if (<= n 0)
0
(if (even? n)
(+ n (sum-even (- n 1)))
(sum-even (- n 1)))))
;; Example usage
(sum-even 10) ; Output: 30
Explanation
even?: Checks if the number is even.
acc (accumulator): Holds the intermediate result for tail recursion.
Both versions stop when n is less than or equal to 0.