Search code examples
schememultiplicationaddition

Multiplication as repeated addition?


I am new to Scheme. I am attempting to write a program that defines (integer) multiplication as repeated addition. In python the program would look something like:

a = int(raw_input(['please enter a number to be multiplied']))
b = int(raw_input(['please enter a number to multiply by']))

y = a
print y
for i in range(b-1):
    y+=a
print y

There are two problems I have when attempting to write in Scheme, one 'hard' and one 'soft':

  1. The 'hard' problem: I cannot find an equivalent of the range function in Scheme. How should I implement this?
  2. The 'soft' problem: At this point in the book, for loops have not been introduced for Scheme, which leads me to believe the solution does not contain a for loop; however, I am fine with using a for loop if that is easier/better.

Solution

  • You use recursion in place of iteration. The general idea is:

    mult(a, b)
        if b == 0, return 0
        return a + mult(a, b-1)
    

    Now, can you code that in Scheme on your own?