0

It is known that in some cases an iteration can be transformed in a recursive algorithm. How can I rewrite an iteration as simple as the following one as a recursion?

for(i=0,i<500,i++) 
    row_multiply();

I realize that, as it has been pointed out, I have to try something like...

void recursiveSolution(int i)

    {
        raw_multiply();
        if (i< 499)
            recursiveSolution(i+ 1);
    }

..., but I am unsure about how to deal with the base case and how to structure coherent C code for the recursive rewrite.

5
  • What have you already tried? Commented Jan 10, 2015 at 1:52
  • Trying something related to recursion would probably be a good place to start (as would be clarifying the question). If you don't understand recursion yet, perhaps study it a bit more before tackling this. An example: see it live Commented Jan 10, 2015 at 2:07
  • What you mean base case?? explain that please. Commented Jan 10, 2015 at 2:13
  • @iharob en.wikipedia.org/wiki/… Commented Jan 10, 2015 at 2:14
  • @user Oh I see, you should have one situation where the function stops recursing, or in simple words, where it stops calling itself, in my sample function, that is when count == 500, there the recursion stops. A very illustrative recursive functions as that of the factorial calculation, google it. And if my answer was useful you can express gratitude by clicking the check mark and accepting it. After all, since the question is closed, no one else can post answers for it. Weired thing it was closed as unclear what you're asking and yet it was answered. Commented Jan 10, 2015 at 2:17

1 Answer 1

1

May be this way?

void recursiveSolution(int count)
{
    raw_multiply();
    if (count < 499)
        recursiveSolution(count + 1);
}

and then to start it

recursiveSolution(0);
Sign up to request clarification or add additional context in comments.

4 Comments

Need to check count < 500 (as the for loop does), before calling raw_multiply() as this would do it 501 times.
raw_multiply needs to be inside the if too, same problem
Could you clarify what you mean by "and then to start it recursiveSolution(0);"?
Well, you need to do a first call to the recursiveSolution() function, after that it will call itself recurse until the condition is met.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.