why do we prefer recursion than while/for loops in writing C programmes??

4 Answers

  • 1 decade ago
    Favorite Answer

    We don't always prefer recursion to while/for loops. We prefer recusion when it fits the model of the problem we are trying to solve. Problems that can be easily broken down into a repeated sub-problem are often more efficiently/easily written through recursion. Other problems are better suited for iterative (loops) solutions.

    Have a look at my source for a more clear explanation.

  • Joe
    Lv 4
    1 decade ago

    When calculating the time complexity of an algorithm, recursion is usually faster than loops. What actually happens is that you trade memory space (recursive functions push into the stack) for time. If you have heard of Big O notation, it will explain this a lot better. For example, A linear bubble sort, which is just a doubly nested loop, has a time complexity of O(N^2), where a merge sort is O(N*log N).

    Sometimes it takes less code using recursion than loops also. However, there are cases where loops are better than recusion. It really depends on the problem.

  • 1 decade ago

    We don't usually. IMHO, recursive iterations should be reserved for times when memory is plentiful compared to the maximum number of times the storage will be allocated to a new function's variables, when execution speed overrides that consideration and when a gracefull bail out is achievable and acceptable. Otherwise, again IMHO, a well done while or for loop is every bit as fast in the user's eyes and more reliable in possible runtime error situations. In other words, it is a valid tool to choose in some rare cirumstances; but like the infamous goto, should probably be avoided where possible.

    Source(s): The twisted mind of me.
  • 1 decade ago

    In addition, recursion is more efficient in situations where while/for loops can take up many more lines of code using more CPU processing cycles than it needs to.


    dlucf said exactly what I was getting at in more detail...

Still have questions? Get your answers by asking now.