Is a while loop intrinsically a recursion

loopsrecursion

I wondered whether a while loop is intrinsically a recursion?

I think it is because a while loop can be seen as a function that calls itself at the end. If it is not recursion, then what is the difference?

Best Answer

Loops are very much not recursion. In fact, they are the prime example of the opposite mechanism: iteration.

The point of recursion is that one element of processing calls another instance of itself. The loop control machinery merely jumps back to the point where it started.

Jumping around in code and calling another block of code are different operations. For instance, when you jump to the start of the loop, the loop control variable still has the same value it had before the jump. But if you call another instance of the routine you're in, then the new instance has new, unrelated copies of all of its variables. Effectively, one variable can have one value on the first level of processing and another value on a lower level.

This capability is crucial for many recursive algorithms to work, and this is why you can't emulate recursion via iteration without also managing a stack of called frames which keeps track of all those values.

Related Topic