Lab 2

Goal:

1. Be able to write a linear recursive procedure in Scheme.

Experiment:

It is occasionally useful to add up the digits in the decimal representation of a nonnegative integer, such as for encryption, hash tables, and casting-out-9s checking of arithmetic operations. Define a procedure called sum-of-digits that takes one argument. We will assume that the argument is a nonnegative integer. The procedure sum-of-digits will return the sum of the digits in the decimal representation of the argument. For example, the procedure will return the following values:
(sum-of-digits 0) --> 0
(sum-of-digits 7) --> 7
(sum-of-digits 1234) --> 10
(sum-of-digits 4792037) --> 32

You will need to use two of Scheme's primitive procedures, remainder and quotient. The procedure call (remainder n 10) will return the last digit of the decimal representation of n, and (quotient n 10) will return the number represented by dropping the last digit of the decimal representation of n. For example, (remainder 1234 10) returns 4, and (quotient 1234 10) returns 123.

Hints: Ask yourself the following questions. They may help you to write the procedure. Do not turn in the answers: they are just for you to think about.

1. Base case: Which nonnegative integers print out as a single digit?

2. Recursive case: How can we break a number n into two numbers such that one of them is a single digit in the decimal representation of n and the other is represented by exactly the remaining digits in the decimal representation of n after the single digit of the first number has been removed from the decimal representation of n? Note that we will eventually want to know the sum of the digits in the representation of this second number, so it is an example of the same problem that we want to solve for n except that it is a smaller number.

3. Recursive relation: Once n has been broken down into two numbers such that the sum of the digits in the decimal representation for each can be known either directly or by a recursive call to sum-of-digits on that number, how can the sums of the digits for these two numbers be combined to get the sum of the digits in the digital representation of n?

Submission

After defining sum-of-digits in DrScheme, checking its syntax, executing it and testing the procedure in the interaction window, and you are satisfied that the procedure definition is correct, save the definition to a file (use Save definition as text), then submit your definition to the Automated Tester and click on the Confirm butten when you get a PASS. Note: The procedure name must be sum-of-digits and no other name. This is because only the procedure sum-of-digits will be called by the test program.