# Recursion

• 10-21-2008
trevordunstan
Recursion
Hey there guys,

I am doing some exercises in my study book for uni and have just started recursion. One of the exercises is use recursion to multiply 2 numbers using repeated addition.

The formula is: M x N = N + (M-1) x N

and the stopping case is 1 x N = N

the exercise says to create a function

int multiply(int m, int n)

I understand the general idea of recursion but am having trouble translating this into code.
Could some one show me how to create the recursive function and just explain the steps they used.

Any help would be great

Thanks
• 10-21-2008
tabstop
Not really; see the homework policy.

But, I suppose I could give you the outline of Every Previous-Answer Recursive Function Ever:
Code:

```int recursive_function(int n) {     if (n == base_case)         return base_answer;     temp = recursive_function(n-1);     return do_nth_step_to_temp; }```
• 10-21-2008
cph
Quote:

Originally Posted by trevordunstan
Hey there guys,

I am doing some exercises in my study book for uni and have just started recursion. One of the exercises is use recursion to multiply 2 numbers using repeated addition.

The formula is: M x N = N + (M-1) x N

and the stopping case is 1 x N = N

the exercise says to create a function

int multiply(int m, int n)

I understand the general idea of recursion but am having trouble translating this into code.
Could some one show me how to create the recursive function and just explain the steps they used.

Any help would be great

Thanks

Code:

```unsigned int rec_func (unsigned int m, unsigned int n) {     return((m == 1)? n : n + rec_func(m - 1, n)); }```
• 10-21-2008
trevordunstan
thanks, that coding worked but i do not understand this bit

return((m == 1)? n :

can you quickly break it down for me.

thanks for the help
• 10-21-2008
cph
Quote:

Originally Posted by trevordunstan
thanks, that coding worked but i do not understand this bit

return((m == 1)? n :

can you quickly break it down for me.

thanks for the help

the function is equal to (someone please correct me if I'm wrong)
Code:

```unsigned int rec_func (unsigned int m, unsigned int n) {     if (m == 1) {         return(n);     }     return(n + rec_func(m - 1, n)); }```
• 10-21-2008
trevordunstan
Yeh thats what I thought,

Thanks for the help, still getting my head around recursion