Recursive Looping

Not that i have used it.

Just idea came in my mind. What if we needed to loop through lots of nested arrays. And for that purpose we used a recursive looping. Which starts looping and at each loop it calls itself.

When i first thought of it. The idea gave me shivers. Why?
Recursive Looping = Forever

Now i am wondering, is there even such a thing. Have you ever come across such code? Or do you think it is even possible?
Last edited on
I guess for looping over deeply nested arrays, if you don't want to make deeply nested loops, you could use recursion. Something like this,

1
2
3
4
5
6
7
8
9
10
11
12
13
loop( array ) 
    for e in array
        do stuff with e

loop ( array, level, depth ) 
    if ( level == depth )
        loop( array )
        return
    for e in array
        loop( e, level + 1, depth )

loop( array, depth )
    loop( array, 0, depth )


Also, it's often very easy to formulate problems recursively and it's pretty common that a recursive solution to a problem makes recursive calls for each iteration of a loop over an input of size n, but the time complexity is exponential with respect to n.

But it's also often possible to make much more efficient algorithms that are only slightly different, still based on the recursive property/nature of the problem, but using dynamic programming techniques instead of recursive function calls at each iteration, to achieve polynomial time complexity, by remembering/using previous results to get further results.

A good example is "Rod Cutting"
http://www.cs.uml.edu/~kdaniels/courses/ALG_503_F12/DynamicRodCutting.pdf

Look up optimal substructure and dynamic programming.


Last edited on
Now i am wondering, is there even such a thing. Have you ever come across such code?

Yes, but it's not as interesting as you seem to think it is. See here: http://en.wikipedia.org/wiki/Stack_overflow#Infinite_recursion

It's not even useful as Mal-ware, as a DoS for example, either since it eventually crashes itself.
I've used such code before for tree traversal for trees with larger numbers of branches per node (in my particular case, I had 26 branches per node).

It's not as scary as it perhaps seems. EDIT: At least, no scarier than recursion.

-Albatross
Last edited on
Wow, actually it seems pretty useful in some cases.

But, it really is scary. I don't think i will ever use it unless last resort.
Topic archived. No new replies allowed.