4/15/2021 0 Comments Recursive C Function
Using recursive algorithm, certain problems can be solved quite easily.Examples of such problems are Towers of Hanoi (TOH), InorderPreorderPostorder Tree Traversals, DFS of Graph, etc.For example, we compute factorial n if we know factorial of (n-1).
![]() Difference between direct and indirect recursion has been illustrated in Table 1. A recursive function calls itself, the memory for a called function is allocated on top of memory allocated to calling function and different copy of local variables is created for each function call. ![]() In statement 2, printFun(2) is called and memory is allocated to printFun(2) and a local variable test is initialized to 2 and statement 1 to 4 are pushed in the stack. Similarly, printFun(2) calls printFun(1) and printFun(1) calls printFun(0). Remaining statements of printFun(1) are executed and it returns to printFun(2) and so on. In the output, value from 3 to 1 are printed and then 1 to 3 are printed. The time complexity of the given program can depend on the function call. The recursive program has greater space requirements than iterative program as all functions will remain in the stack until the base case is reached. It also has greater time requirements because of function calls and returns overhead. Some problems are inherently recursive like tree traversals, Tower of Hanoi, etc. For example refer Inorder Tree Traversal without Recursion, Iterative Tower of Hanoi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contributegeeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |