0% found this document useful (0 votes)
3 views1 page

Scheme Program for Even Number Sum

The document provides a Scheme program to calculate the sum of even numbers up to a given number n using both tail recursion and normal recursion. The tail recursion implementation optimizes memory by making the recursive call the last operation, while the normal recursion does not optimize memory. Example usages for both implementations are included, showing that both return a sum of 30 for the input of 10.

Uploaded by

A I M E N
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views1 page

Scheme Program for Even Number Sum

The document provides a Scheme program to calculate the sum of even numbers up to a given number n using both tail recursion and normal recursion. The tail recursion implementation optimizes memory by making the recursive call the last operation, while the normal recursion does not optimize memory. Example usages for both implementations are included, showing that both return a sum of 30 for the input of 10.

Uploaded by

A I M E N
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

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.

You might also like