What is the difference between iteration and recursion?

后端 未结 8 787
太阳男子
太阳男子 2021-01-30 11:52

What is the difference between iteration and recursion and why/when is one better:

while (true) {
    // Iterating
}

8条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-30 12:19

    Differences between recursion and iteration

    Recursion

    1. Recursive function – is a function that is partially defined by itself
    2. Recursion uses selection structure
    3. Infinite recursion occurs if the recursion step does not reduce the problem in a manner that converges on some condition (base case)
    4. Recursion terminates when a base case is recognized
    5. Recursion is usually slower than iteration due to overhead of maintaining stack
    6. Recursion uses more memory than iteration
    7. Infinite recursion can crash the system
    8. Recursion makes code smaller

    Iteration

    1. Iterative Instructions – are loop based repetitions of a process
    2. Iteration uses repetition structure
    3. An infinite loop occurs with iteration if the loop condition test never becomes false
    4. Iteration terminates when the loop condition fails
    5. Iteration does not use the stack so it's faster than recursion
    6. Iteration consumes less memory
    7. Infinite looping uses CPU cycles repeatedly
    8. Iteration makes code longer

    Data taken from here.

提交回复
热议问题