If we don't know how many for we should use,should we use recursive function?

If this is your first visit, be sure to
check out the FAQ by clicking the
link above. You may have to register or Login
before you can post: click the register link above to proceed. To start viewing messages,
select the forum that you want to visit from the selection below.

If we don't know how many for we should use,should we use recursive function?

Let's say that we don't know how many "for loops" we need before the program starts and user inputs a number,should we use recursive function instead of "for loops"?Or is there a way to do it using "for loops"?

Re: If we don't know how many for we should use,should we use recursive function?

What you ask for can be done using a for loop, but perhaps a while loop would be more appropriate. It depends on the specifics. Without tail recursion optimisation, recursion could be worse as there is a maximum recursive depth before say, stack space runs out.

Re: If we don't know how many for we should use,should we use recursive function?

Originally Posted by AwArEnEsS

Let's say that we don't know how many "for loops" we need before the program starts and user inputs a number,should we use recursive function instead of "for loops"?Or is there a way to do it using "for loops"?

Re: If we don't know how many for we should use,should we use recursive function?

Originally Posted by AwArEnEsS

Let's say that we don't know how many "for loops" we need before the program starts and user inputs a number,should we use recursive function instead of "for loops"?Or is there a way to do it using "for loops"?

In the situation you mention there's no difference in principle. In both cases you need a stop criterion to know when to stop iterating or when to stop making recursive calls. In fact iteration and recursion are equivalent. You can always turn one into the other.

Traditionally in procedural languages such as C++ recursion is used mostly when the problem at hand has a very pronounced recursive structure and I don't feel that's the case here. I and probably more than 99% of whoever you ask would use iteration.

I am trying to turn these codes into a program which uses for loop instead of recursive function,but I couldn't.In the book it says "you can do the same using for loop instead of recursive function" but it doesn't write how we can do it.Also,I need the answer in C not C++ please.

Re: If we don't know how many for we should use,should we use recursive function?

I am trying to turn these codes into a program which uses for loop instead of recursive function,but I couldn't.In the book it says "you can do the same using for loop instead of recursive function" but it doesn't write how we can do it.Also,I need the answer in C not C++ please.